file_id
int64
1
215k
content
stringlengths
7
454k
repo
stringlengths
6
113
path
stringlengths
6
251
213,983
/*[INCLUDE-IF Sidecar18-SE]*/ /* * Copyright IBM Corp. and others 2008 * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution and * is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] https://openjdk.org/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 OR GPL-2.0-only WITH OpenJDK-assembly-exception-1.0 */ package com.ibm.dtfj.phd; import java.util.Properties; import com.ibm.dtfj.image.CorruptDataException; import com.ibm.dtfj.image.DataUnavailable; import com.ibm.dtfj.image.ImageAddressSpace; import com.ibm.dtfj.image.ImagePointer; import com.ibm.dtfj.image.MemoryAccessException; /** * @author ajohnson */ class PHDImagePointer implements ImagePointer { private final ImageAddressSpace space; private final long addr; PHDImagePointer(ImageAddressSpace imageAddress, long arg0) { space = imageAddress; addr = arg0; } public ImagePointer add(long arg0) { return new PHDImagePointer(space,addr+arg0); } public long getAddress() { return addr; } public ImageAddressSpace getAddressSpace() { return space; } public byte getByteAt(long arg0) throws MemoryAccessException, CorruptDataException { throw new MemoryAccessException(add(arg0)); } public double getDoubleAt(long arg0) throws MemoryAccessException, CorruptDataException { throw new MemoryAccessException(add(arg0)); } public float getFloatAt(long arg0) throws MemoryAccessException, CorruptDataException { throw new MemoryAccessException(add(arg0)); } public int getIntAt(long arg0) throws MemoryAccessException, CorruptDataException { throw new MemoryAccessException(add(arg0)); } public long getLongAt(long arg0) throws MemoryAccessException, CorruptDataException { throw new MemoryAccessException(add(arg0)); } public ImagePointer getPointerAt(long arg0) throws MemoryAccessException, CorruptDataException { throw new MemoryAccessException(add(arg0)); } public short getShortAt(long arg0) throws MemoryAccessException, CorruptDataException { throw new MemoryAccessException(add(arg0)); } public boolean isExecutable() throws DataUnavailable { throw new DataUnavailable(); } public boolean isReadOnly() throws DataUnavailable { throw new DataUnavailable(); } public boolean isShared() throws DataUnavailable { throw new DataUnavailable(); } public Properties getProperties() { return new Properties(); } public boolean equals(Object o) { if (o instanceof PHDImagePointer) { PHDImagePointer to = (PHDImagePointer)o; if (space.equals(to.space) && addr == to.addr) return true; } return false; } public int hashCode() { return space.hashCode() ^ (int)addr ^ (int)(addr >>> 32); } }
eclipse-openj9/openj9
jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/phd/PHDImagePointer.java
213,984
/* * This class is based on the C# open source freeware library Clipper: * http://www.angusj.com/delphi/clipper.php * The original classes were distributed under the Boost Software License: * * Freeware for both open source and commercial applications * Copyright 2010-2014 Angus Johnson * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.itextpdf.kernel.pdf.canvas.parser.clipper; import java.util.ArrayList; /** * A pure convenience class to avoid writing {@code List<Path>} everywhere. */ public class Paths extends ArrayList<Path> { public static Paths closedPathsFromPolyTree( PolyTree polytree ) { final Paths result = new Paths(); // result.Capacity = polytree.Total; result.addPolyNode( polytree, PolyNode.NodeType.CLOSED ); return result; } public static Paths makePolyTreeToPaths( PolyTree polytree ) { final Paths result = new Paths(); // result.Capacity = polytree.Total; result.addPolyNode( polytree, PolyNode.NodeType.ANY ); return result; } public static Paths openPathsFromPolyTree( PolyTree polytree ) { final Paths result = new Paths(); // result.Capacity = polytree.ChildCount; for (final PolyNode c : polytree.getChilds()) { if (c.isOpen()) { result.add( c.getPolygon() ); } } return result; } /** * */ public Paths() { super(); } public Paths( int initialCapacity ) { super( initialCapacity ); } public void addPolyNode( PolyNode polynode, PolyNode.NodeType nt ) { boolean match = true; switch (nt) { case OPEN: return; case CLOSED: match = !polynode.isOpen(); break; default: break; } if (polynode.getPolygon().size() > 0 && match) { add( polynode.getPolygon() ); } for (final PolyNode pn : polynode.getChilds()) { addPolyNode( pn, nt ); } } public Paths cleanPolygons() { return cleanPolygons( 1.415 ); } public Paths cleanPolygons( double distance ) { final Paths result = new Paths( size() ); for (int i = 0; i < size(); i++) { result.add( get( i ).cleanPolygon( distance ) ); } return result; } public LongRect getBounds() { int i = 0; final int cnt = size(); final LongRect result = new LongRect(); while (i < cnt && get( i ).isEmpty()) { i++; } if (i == cnt) { return result; } result.left = get( i ).get( 0 ).getX(); result.right = result.left; result.top = get( i ).get( 0 ).getY(); result.bottom = result.top; for (; i < cnt; i++) { for (int j = 0; j < get( i ).size(); j++) { if (get( i ).get( j ).getX() < result.left) { result.left = get( i ).get( j ).getX(); } else if (get( i ).get( j ).getX() > result.right) { result.right = get( i ).get( j ).getX(); } if (get( i ).get( j ).getY() < result.top) { result.top = get( i ).get( j ).getY(); } else if (get( i ).get( j ).getY() > result.bottom) { result.bottom = get( i ).get( j ).getY(); } } } return result; } public void reversePaths() { for (final Path poly : this) { poly.reverse(); } } }
itext/itext-java
kernel/src/main/java/com/itextpdf/kernel/pdf/canvas/parser/clipper/Paths.java
213,985
package com.hbm.main; import com.hbm.animloader.AnimatedModel; import com.hbm.animloader.Animation; import com.hbm.animloader.ColladaLoader; import com.hbm.lib.RefStrings; import com.hbm.render.loader.HFRWavefrontObject; import com.hbm.render.loader.WavefrontObjDisplayList; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.AdvancedModelLoader; import net.minecraftforge.client.model.IModelCustom; public class ResourceManager { //public static final Shader test_shader = ShaderManager.loadShader(new ResourceLocation(RefStrings.MODID, "shaders/test_shader")); //God public static final IModelCustom error = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/error.obj")); ////Obj TEs //Turrets public static final IModelCustom turret_heavy_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_heavy_base.obj")); public static final IModelCustom turret_heavy_rotor = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_heavy_rotor.obj")); public static final IModelCustom turret_spitfire_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_spitfire_base.obj")); public static final IModelCustom turret_spitfire_rotor = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_spitfire_rotor.obj")); public static final IModelCustom turret_cwis_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/cwis_base.obj")); public static final IModelCustom turret_cwis_rotor = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/cwis_rotor.obj")); public static final IModelCustom turret_cheapo_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_cheapo_base.obj")); public static final IModelCustom turret_cheapo_rotor = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_cheapo_rotor.obj")); public static final IModelCustom turret_heavy_gun = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_heavy_gun.obj")); public static final IModelCustom turret_rocket_gun = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_rocket_gun.obj")); public static final IModelCustom turret_light_gun = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_light_gun.obj")); public static final IModelCustom turret_flamer_gun = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_flamer_gun.obj")); public static final IModelCustom turret_tau_gun = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_tau_gun.obj")); public static final IModelCustom turret_spitfire_gun = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_spitfire_gun.obj")); public static final IModelCustom turret_cwis_head = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/cwis_head.obj")); public static final IModelCustom turret_cwis_gun = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/cwis_gun.obj")); public static final IModelCustom turret_cheapo_head = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_cheapo_head.obj")); public static final IModelCustom turret_cheapo_gun = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turret_cheapo_gun.obj")); public static final IModelCustom turret_chekhov = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_chekhov.obj")); public static final IModelCustom turret_jeremy = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_jeremy.obj")); public static final IModelCustom turret_tauon = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_tauon.obj")); public static final IModelCustom turret_richard = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_richard.obj")); public static final IModelCustom turret_howard = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_howard.obj")); public static final IModelCustom turret_maxwell = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_microwave.obj")); public static final IModelCustom turret_fritz = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_fritz.obj")); public static final IModelCustom turret_brandon = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_brandon.obj")); public static final IModelCustom turret_arty = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_arty.obj")).asDisplayList(); // test! public static final IModelCustom turret_himars = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_himars.obj")).asDisplayList(); public static final IModelCustom turret_howard_damaged = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/turrets/turret_howard_damaged.obj")); //Heaters public static final IModelCustom heater_firebox = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/firebox.obj")); public static final IModelCustom heater_oven = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/heating_oven.obj")); public static final IModelCustom heater_oilburner = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/oilburner.obj")); public static final IModelCustom heater_electric = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/electric_heater.obj"), false); //Heat Engines public static final IModelCustom stirling = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/stirling.obj")); public static final IModelCustom sawmill = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/sawmill.obj")); public static final IModelCustom crucible_heat = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/crucible.obj")); public static final IModelCustom boiler = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/boiler.obj")); public static final IModelCustom boiler_burst = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/boiler_burst.obj")); //Furnaces public static final IModelCustom furnace_iron = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/furnace_iron.obj")); public static final IModelCustom furnace_steel = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/furnace_steel.obj")); //Landmines public static final IModelCustom mine_ap = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/mine_ap.obj")); public static final IModelCustom mine_he = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/mine_he.obj")); public static final IModelCustom mine_marelet = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/bombs/marelet.obj")); public static final IModelCustom mine_fat = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/mine_fat.obj")); //Oil Pumps public static final IModelCustom derrick = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/derrick.obj")); public static final IModelCustom pumpjack = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/pumpjack.obj")); public static final IModelCustom fracking_tower = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/fracking_tower.obj")); //Refinery public static final IModelCustom refinery = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/refinery.obj")); public static final IModelCustom fraction_tower = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/fraction_tower.obj")); public static final IModelCustom fraction_spacer = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/fraction_spacer.obj")); public static final IModelCustom cracking_tower = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/cracking_tower.obj")); public static final IModelCustom liquefactor = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/liquefactor.obj")); public static final IModelCustom solidifier = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/solidifier.obj")); //Flare Stack public static final IModelCustom oilflare = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/flare_stack.obj")); //Tank public static final IModelCustom fluidtank = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/fluidtank.obj")); public static final IModelCustom bat9000 = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/bat9000.obj")); public static final IModelCustom orbus = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/orbus.obj")); //Turbofan public static final IModelCustom turbofan_body = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turbofan_body.obj")); public static final IModelCustom turbofan_blades = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/turbofan_blades.obj")); public static final IModelCustom turbofan = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/turbofan.obj")); //Large Turbine public static final IModelCustom steam_engine = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/steam_engine.obj")).asDisplayList(); public static final IModelCustom turbine = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/turbine.obj")); public static final IModelCustom chungus = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/chungus.obj")).asDisplayList(); //Cooling Tower public static final IModelCustom tower_small = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/tower_small.obj")); public static final IModelCustom tower_large = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/tower_large.obj")); //IGen public static final IModelCustom igen = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/igen.obj")); //Selenium Engine public static final IModelCustom selenium_body = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/selenium_engine_body.obj")); public static final IModelCustom selenium_rotor = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/selenium_engine_rotor.obj")); public static final IModelCustom selenium_piston = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/selenium_engine_piston.obj")); //Press public static final IModelCustom press_body = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/press_body.obj")); public static final IModelCustom press_head = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/press_head.obj")); public static final IModelCustom epress_body = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/epress_body.obj")); public static final IModelCustom epress_head = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/epress_head.obj")); //Assembler public static final IModelCustom assembler_body = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/assembler_new_body.obj")); public static final IModelCustom assembler_cog = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/assembler_new_cog.obj")); public static final IModelCustom assembler_slider = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/assembler_new_slider.obj")); public static final IModelCustom assembler_arm = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/assembler_new_arm.obj")); public static final IModelCustom assemfac = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/assemfac.obj")); //Chemplant public static final IModelCustom chemplant_body = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/chemplant_new_body.obj")); public static final IModelCustom chemplant_spinner = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/chemplant_new_spinner.obj")); public static final IModelCustom chemplant_piston = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/chemplant_new_piston.obj")); public static final IModelCustom chemplant_fluid = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/chemplant_new_fluid.hmf")); public static final IModelCustom chemplant_fluidcap = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/chemplant_new_fluidcap.hmf")); public static final IModelCustom chemfac = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/chemfac.obj")); //F6 TANKS public static final IModelCustom tank = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/tank.obj")); //Centrifuge public static final IModelCustom centrifuge = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/centrifuge.obj")); public static final IModelCustom gascent = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/gascent.obj")); public static final IModelCustom silex = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/silex.obj")); public static final IModelCustom fel = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/fel.obj")); //Magnusson Device public static final IModelCustom microwave = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/microwave.obj")); //Mining Drill public static final IModelCustom drill_body = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/drill_main.obj")); public static final IModelCustom drill_bolt = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/drill_bolt.obj")); //Laser Miner public static final IModelCustom mining_laser = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/mining_laser.obj")); //Crystallizer public static final IModelCustom crystallizer = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/crystallizer.obj")); //Cyclotron public static final IModelCustom cyclotron = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/cyclotron.obj")); //RTG public static final IModelCustom rtg = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/rtg.obj")); //Waste Drum public static final IModelCustom waste_drum = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/drum.obj")); //Deuterium Tower public static final IModelCustom deuterium_tower = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/machine_deuterium_tower.obj")); //Anti Mass Spectrometer public static final IModelCustom ams_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/ams_base.obj")); public static final IModelCustom ams_emitter = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/ams_emitter.obj")); public static final IModelCustom ams_emitter_destroyed = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/ams_emitter_destroyed.obj")); public static final IModelCustom ams_limiter = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/ams_limiter.obj")); public static final IModelCustom ams_limiter_destroyed = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/ams_limiter_destroyed.obj")); //Dark Matter Core public static final IModelCustom dfc_emitter = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/core_emitter.obj")); public static final IModelCustom dfc_receiver = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/core_receiver.obj")); public static final IModelCustom dfc_injector = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/core_injector.obj")); //Sphere public static final IModelCustom sphere_ruv = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sphere_ruv.obj")); public static final IModelCustom sphere_iuv = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sphere_iuv.obj")); public static final IModelCustom sphere_uv = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sphere_uv.obj")); public static final IModelCustom sphere_uv_anim = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sphere_uv.hmf")); //Meteor public static final IModelCustom meteor = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/weapons/meteor.obj")); //Radgen public static final IModelCustom radgen = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/radgen.obj")); //Small Reactor public static final IModelCustom reactor_small_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/reactors/reactor_small_base.obj")); public static final IModelCustom reactor_small_rods = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/reactors/reactor_small_rods.obj")); //Breeder public static final IModelCustom breeder = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/reactors/breeder.obj")); //ITER public static final IModelCustom iter = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/reactors/iter.obj")); //Watz public static final IModelCustom watz = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/reactors/watz.obj")); //FENSU public static final IModelCustom fensu = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/fensu.obj")); //Radar public static final IModelCustom radar_body = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/radar_base.obj")); public static final IModelCustom radar_head = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/radar_head.obj")); public static final IModelCustom radar = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/radar.obj")); //Forcefield public static final IModelCustom forcefield_top = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/forcefield_top.obj")); //Shredder public static final IModelCustom shredder = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/shredder.obj")); //Bombs public static final IModelCustom bomb_gadget = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/TheGadget3.obj")); public static final IModelCustom bomb_boy = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/LilBoy1.obj")); public static final IModelCustom bomb_man = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/FatMan.obj")).asDisplayList(); public static final IModelCustom bomb_mike = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/IvyMike.obj")); public static final IModelCustom bomb_tsar = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/TsarBomba.obj")); public static final IModelCustom bomb_prototype = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/Prototype.obj")); public static final IModelCustom bomb_fleija = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/Fleija.obj")); public static final IModelCustom bomb_solinium = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/bombs/ufp.obj")); public static final IModelCustom n2 = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/bombs/n2.obj")); public static final IModelCustom bomb_multi = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/BombGeneric.obj")); public static final IModelCustom n45_globe = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/bombs/n45_globe.obj")); public static final IModelCustom n45_knob = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/bombs/n45_knob.obj")); public static final IModelCustom n45_rod = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/bombs/n45_rod.obj")); public static final IModelCustom n45_stand = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/bombs/n45_stand.obj")); public static final IModelCustom n45_chain = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/bombs/n45_chain.obj")); public static final IModelCustom fstbmb = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/bombs/fstbmb.obj")); public static final IModelCustom dud = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/BalefireCrashed.obj")); //Cel-Prime public static final IModelCustom cp_tower = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/cel_prime_tower.obj")); public static final IModelCustom cp_terminal = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/cel_prime_terminal.obj")); public static final IModelCustom cp_battery = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/cel_prime_battery.obj")); public static final IModelCustom cp_tanks = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/cel_prime_tanks.obj")); public static final IModelCustom cp_port = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/cel_prime_port.obj")); //Satellites public static final IModelCustom sat_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sat_base.obj")); public static final IModelCustom sat_radar = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sat_radar.obj")); public static final IModelCustom sat_resonator = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sat_resonator.obj")); public static final IModelCustom sat_scanner = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sat_scanner.obj")); public static final IModelCustom sat_mapper = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sat_mapper.obj")); public static final IModelCustom sat_laser = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sat_laser.obj")); public static final IModelCustom sat_foeq = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sat_foeq.obj")); public static final IModelCustom sat_foeq_burning = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sat_foeq_burning.obj")); public static final IModelCustom sat_foeq_fire = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sat_foeq_fire.obj")); //SatDock public static final IModelCustom satDock = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sat_dock.obj")); //Solar Tower public static final IModelCustom solar_boiler = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/solar_boiler.obj")); public static final IModelCustom solar_mirror = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/machines/solar_mirror.obj")); //Vault Door public static final IModelCustom vault_cog = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/vault_cog.obj")); public static final IModelCustom vault_frame = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/vault_frame.obj")); public static final IModelCustom vault_teeth = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/vault_teeth.obj")); public static final IModelCustom vault_label = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/vault_label.obj")); //Blast Door public static final IModelCustom blast_door_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blast_door_base.obj")); public static final IModelCustom blast_door_tooth = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blast_door_tooth.obj")); public static final IModelCustom blast_door_slider = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blast_door_slider.obj")); public static final IModelCustom blast_door_block = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blast_door_block.obj")); //Doors public static AnimatedModel transition_seal; public static Animation transition_seal_anim; public static final WavefrontObjDisplayList fire_door = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/doors/fire_door.obj")).asDisplayList(); //Tesla Coil public static final IModelCustom tesla = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/tesla.obj")); public static final IModelCustom teslacrab = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/mobs/teslacrab.obj")); public static final IModelCustom taintcrab = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/mobs/taintcrab.obj")); public static final IModelCustom maskman = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/mobs/maskman.obj")); public static final IModelCustom spider = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/mobs/blockspider.obj")); public static final IModelCustom ufo = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/mobs/ufo.obj")); public static final IModelCustom mini_ufo = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/mobs/mini_ufo.obj")); public static final IModelCustom siege_ufo = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/mobs/siege_ufo.obj")); //ZIRNOX public static final IModelCustom zirnox = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/zirnox.obj")); public static final IModelCustom zirnox_destroyed = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/zirnox_destroyed.obj")); //Belt public static final IModelCustom arrow = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/arrow.obj")); //Network public static final IModelCustom connector = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/network/connector.obj")); public static final IModelCustom pylon_large = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/network/pylon_large.obj")); public static final IModelCustom substation = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/network/substation.obj")); //Radiolysis public static final IModelCustom radiolysis = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/radiolysis.obj")); //Electrolyser public static final IModelCustom electrolyser = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/machines/electrolyser.obj")); //Belt public static final IModelCustom charger = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/blocks/charger.obj")); //DecoContainer (File Cabinet for now) public static final IModelCustom file_cabinet = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/file_cabinet.obj")); ////Textures TEs public static final ResourceLocation universal = new ResourceLocation(RefStrings.MODID, "textures/models/TheGadget3_.png"); public static final ResourceLocation universal_bright = new ResourceLocation(RefStrings.MODID, "textures/models/turbofan_blades.png"); public static final ResourceLocation turret_heavy_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_heavy_base.png"); public static final ResourceLocation turret_heavy_rotor_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_heavy_rotor.png"); public static final ResourceLocation turret_heavy_gun_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_heavy_gun.png"); public static final ResourceLocation turret_light_rotor_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_light_rotor.png"); public static final ResourceLocation turret_light_gun_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_light_gun.png"); public static final ResourceLocation turret_rocket_rotor_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_rocket_rotor.png"); public static final ResourceLocation turret_rocket_gun_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_rocket_gun.png"); public static final ResourceLocation turret_flamer_rotor_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_flamer_rotor.png"); public static final ResourceLocation turret_flamer_gun_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_flamer_gun.png"); public static final ResourceLocation turret_tau_rotor_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_tau_rotor.png"); public static final ResourceLocation turret_tau_gun_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_tau_gun.png"); public static final ResourceLocation turret_ciws_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/cwis_base.png"); public static final ResourceLocation turret_ciws_rotor_tex = new ResourceLocation(RefStrings.MODID, "textures/models/cwis_rotor.png"); public static final ResourceLocation turret_ciws_head_tex = new ResourceLocation(RefStrings.MODID, "textures/models/cwis_head.png"); public static final ResourceLocation turret_ciws_gun_tex = new ResourceLocation(RefStrings.MODID, "textures/models/cwis_gun.png"); public static final ResourceLocation turret_cheapo_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_cheapo_base.png"); public static final ResourceLocation turret_cheapo_rotor_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_cheapo_rotor.png"); public static final ResourceLocation turret_cheapo_head_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_cheapo_head.png"); public static final ResourceLocation turret_cheapo_gun_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turret_cheapo_gun.png"); public static final ResourceLocation turret_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/base.png"); public static final ResourceLocation turret_base_friendly_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/base_friendly.png"); public static final ResourceLocation turret_carriage_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/carriage.png"); public static final ResourceLocation turret_carriage_ciws_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/carriage_ciws.png"); public static final ResourceLocation turret_carriage_friendly_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/carriage_friendly.png"); public static final ResourceLocation turret_connector_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/connector.png"); public static final ResourceLocation turret_chekhov_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/chekhov.png"); public static final ResourceLocation turret_chekhov_barrels_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/chekhov_barrels.png"); public static final ResourceLocation turret_jeremy_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/jeremy.png"); public static final ResourceLocation turret_tauon_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/tauon.png"); public static final ResourceLocation turret_richard_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/richard.png"); public static final ResourceLocation turret_howard_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/howard.png"); public static final ResourceLocation turret_howard_barrels_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/howard_barrels.png"); public static final ResourceLocation turret_maxwell_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/maxwell.png"); public static final ResourceLocation turret_fritz_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/fritz.png"); public static final ResourceLocation turret_brandon_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/brandon.png"); public static final ResourceLocation turret_arty_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/arty.png"); public static final ResourceLocation turret_himars_tex = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/himars.png"); public static final ResourceLocation himars_standard_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/himars_standard.png"); public static final ResourceLocation himars_single_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/himars_single.png"); public static final ResourceLocation turret_base_rusted= new ResourceLocation(RefStrings.MODID, "textures/models/turrets/rusted/base.png"); public static final ResourceLocation turret_carriage_ciws_rusted = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/rusted/carriage_ciws.png"); public static final ResourceLocation turret_howard_rusted = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/rusted/howard.png"); public static final ResourceLocation turret_howard_barrels_rusted = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/rusted/howard_barrels.png"); public static final ResourceLocation brandon_explosive = new ResourceLocation(RefStrings.MODID, "textures/models/turrets/brandon_drum.png"); //Landmines public static final ResourceLocation mine_ap_tex = new ResourceLocation(RefStrings.MODID, "textures/models/mine_ap.png"); //public static final ResourceLocation mine_he_tex = new ResourceLocation(RefStrings.MODID, "textures/models/mine_he.png"); public static final ResourceLocation mine_marelet_tex = new ResourceLocation(RefStrings.MODID, "textures/models/bombs/mine_marelet.png"); public static final ResourceLocation mine_shrap_tex = new ResourceLocation(RefStrings.MODID, "textures/models/mine_shrap.png"); public static final ResourceLocation mine_fat_tex = new ResourceLocation(RefStrings.MODID, "textures/models/mine_fat.png"); //Heaters public static final ResourceLocation heater_firebox_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/firebox.png"); public static final ResourceLocation heater_oven_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/heating_oven.png"); public static final ResourceLocation heater_oilburner_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/oilburner.png"); public static final ResourceLocation heater_electric_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/electric_heater.png"); //Heat Engines public static final ResourceLocation stirling_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/stirling.png"); public static final ResourceLocation stirling_steel_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/stirling_steel.png"); public static final ResourceLocation sawmill_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/sawmill.png"); public static final ResourceLocation crucible_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/crucible_heat.png"); public static final ResourceLocation boiler_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/boiler.png"); //Furnaces public static final ResourceLocation furnace_iron_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/furnace_iron.png"); public static final ResourceLocation furnace_steel_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/furnace_steel.png"); //Oil Pumps public static final ResourceLocation derrick_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/derrick.png"); public static final ResourceLocation pumpjack_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/pumpjack.png"); public static final ResourceLocation fracking_tower_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/fracking_tower.png"); //Refinery public static final ResourceLocation refinery_tex = new ResourceLocation(RefStrings.MODID, "textures/models/refinery.png"); public static final ResourceLocation fraction_tower_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/fraction_tower.png"); public static final ResourceLocation fraction_spacer_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/fraction_spacer.png"); public static final ResourceLocation cracking_tower_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/cracking_tower.png"); public static final ResourceLocation liquefactor_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/liquefactor.png"); public static final ResourceLocation solidifier_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/solidifier.png"); //Flare Stack public static final ResourceLocation oilflare_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/flare_stack.png"); //Tank public static final ResourceLocation tank_tex = new ResourceLocation(RefStrings.MODID, "textures/models/tank.png"); public static final ResourceLocation tank_label_tex = new ResourceLocation(RefStrings.MODID, "textures/models/tank/tank_NONE.png"); public static final ResourceLocation bat9000_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/bat9000.png"); public static final ResourceLocation orbus_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/orbus.png"); //Turbofan public static final ResourceLocation turbofan_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/turbofan.png"); public static final ResourceLocation turbofan_back_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/turbofan_back.png"); public static final ResourceLocation turbofan_afterburner_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/turbofan_afterburner.png"); //Large Turbine public static final ResourceLocation steam_engine_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/steam_engine.png"); public static final ResourceLocation turbine_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/turbine.png"); public static final ResourceLocation chungus_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/chungus.png"); //Cooling Tower public static final ResourceLocation tower_small_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/tower_small.png"); public static final ResourceLocation tower_large_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/tower_large.png"); //Deuterium Tower public static final ResourceLocation deuterium_tower_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/machine_deuterium_tower.png"); //IGen public static final ResourceLocation igen_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/igen.png"); public static final ResourceLocation igen_rotor = new ResourceLocation(RefStrings.MODID, "textures/models/machines/igen_rotor.png"); public static final ResourceLocation igen_cog = new ResourceLocation(RefStrings.MODID, "textures/models/machines/igen_cog.png"); public static final ResourceLocation igen_arm = new ResourceLocation(RefStrings.MODID, "textures/models/machines/igen_arm.png"); public static final ResourceLocation igen_pistons = new ResourceLocation(RefStrings.MODID, "textures/models/machines/igen_pistons.png"); //Selenium Engine public static final ResourceLocation selenium_body_tex = new ResourceLocation(RefStrings.MODID, "textures/models/selenium_engine_body.png"); public static final ResourceLocation selenium_piston_tex = new ResourceLocation(RefStrings.MODID, "textures/models/selenium_engine_piston.png"); public static final ResourceLocation selenium_rotor_tex = new ResourceLocation(RefStrings.MODID, "textures/models/selenium_engine_rotor.png"); //Press public static final ResourceLocation press_body_tex = new ResourceLocation(RefStrings.MODID, "textures/models/press_body.png"); public static final ResourceLocation press_head_tex = new ResourceLocation(RefStrings.MODID, "textures/models/press_head.png"); public static final ResourceLocation epress_body_tex = new ResourceLocation(RefStrings.MODID, "textures/models/epress_body.png"); public static final ResourceLocation epress_head_tex = new ResourceLocation(RefStrings.MODID, "textures/models/epress_head.png"); //Assembler public static final ResourceLocation assembler_body_tex = new ResourceLocation(RefStrings.MODID, "textures/models/assembler_base_new.png"); public static final ResourceLocation assembler_cog_tex = new ResourceLocation(RefStrings.MODID, "textures/models/assembler_cog_new.png"); public static final ResourceLocation assembler_slider_tex = new ResourceLocation(RefStrings.MODID, "textures/models/assembler_slider_new.png"); public static final ResourceLocation assembler_arm_tex = new ResourceLocation(RefStrings.MODID, "textures/models/assembler_arm_new.png"); public static final ResourceLocation assemfac_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/assemfac.png"); //Chemplant public static final ResourceLocation chemplant_body_tex = new ResourceLocation(RefStrings.MODID, "textures/models/chemplant_base_new.png"); public static final ResourceLocation chemplant_spinner_tex = new ResourceLocation(RefStrings.MODID, "textures/models/chemplant_spinner_new.png"); public static final ResourceLocation chemplant_piston_tex = new ResourceLocation(RefStrings.MODID, "textures/models/chemplant_piston_new.png"); public static final ResourceLocation chemplant_fluid_tex = new ResourceLocation(RefStrings.MODID, "textures/models/lavabase_small.png"); public static final ResourceLocation chemfac_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/chemfac.png"); //F6 TANKS public static final ResourceLocation uf6_tex = new ResourceLocation(RefStrings.MODID, "textures/models/UF6Tank.png"); public static final ResourceLocation puf6_tex = new ResourceLocation(RefStrings.MODID, "textures/models/PUF6Tank.png"); //Centrifuge public static final ResourceLocation centrifuge_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/centrifuge.png"); public static final ResourceLocation gascent_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/gascent.png"); public static final ResourceLocation fel_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/fel.png"); public static final ResourceLocation silex_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/silex.png"); //Magnusson Device public static final ResourceLocation microwave_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/microwave.png"); //Mining Drill public static final ResourceLocation drill_body_tex = new ResourceLocation(RefStrings.MODID, "textures/models/mining_drill.png"); public static final ResourceLocation drill_bolt_tex = new ResourceLocation(RefStrings.MODID, "textures/models/textureIGenRotor.png"); //Laser Miner public static final ResourceLocation mining_laser_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/mining_laser_base.png"); public static final ResourceLocation mining_laser_pivot_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/mining_laser_pivot.png"); public static final ResourceLocation mining_laser_laser_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/mining_laser_laser.png"); //Crystallizer public static final ResourceLocation crystallizer_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/crystallizer.png"); public static final ResourceLocation crystallizer_spinner_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/crystallizer_spinner.png"); public static final ResourceLocation crystallizer_window_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/crystallizer_window.png"); //Cyclotron public static final ResourceLocation cyclotron_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/cyclotron.png"); public static final ResourceLocation cyclotron_ashes = new ResourceLocation(RefStrings.MODID, "textures/models/machines/cyclotron_ashes.png"); public static final ResourceLocation cyclotron_ashes_filled = new ResourceLocation(RefStrings.MODID, "textures/models/machines/cyclotron_ashes_filled.png"); public static final ResourceLocation cyclotron_book = new ResourceLocation(RefStrings.MODID, "textures/models/machines/cyclotron_book.png"); public static final ResourceLocation cyclotron_book_filled = new ResourceLocation(RefStrings.MODID, "textures/models/machines/cyclotron_book_filled.png"); public static final ResourceLocation cyclotron_gavel = new ResourceLocation(RefStrings.MODID, "textures/models/machines/cyclotron_gavel.png"); public static final ResourceLocation cyclotron_gavel_filled = new ResourceLocation(RefStrings.MODID, "textures/models/machines/cyclotron_gavel_filled.png"); public static final ResourceLocation cyclotron_coin = new ResourceLocation(RefStrings.MODID, "textures/models/machines/cyclotron_coin.png"); public static final ResourceLocation cyclotron_coin_filled = new ResourceLocation(RefStrings.MODID, "textures/models/machines/cyclotron_coin_filled.png"); //RTG public static final ResourceLocation rtg_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/rtg.png"); public static final ResourceLocation rtg_cell_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/rtg_cell.png"); public static final ResourceLocation rtg_polonium_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/rtg_polonium.png"); //Waste Drum public static final ResourceLocation waste_drum_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/drum_gray.png"); //Anti Mass Spectrometer public static final ResourceLocation ams_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/ams_base.png"); public static final ResourceLocation ams_emitter_tex = new ResourceLocation(RefStrings.MODID, "textures/models/ams_emitter.png"); public static final ResourceLocation ams_limiter_tex = new ResourceLocation(RefStrings.MODID, "textures/models/ams_limiter.png"); public static final ResourceLocation ams_destroyed_tex = new ResourceLocation(RefStrings.MODID, "textures/models/ams_destroyed.png"); //Dark Matter Core public static final ResourceLocation dfc_emitter_tex = new ResourceLocation(RefStrings.MODID, "textures/models/core_emitter.png"); public static final ResourceLocation dfc_receiver_tex = new ResourceLocation(RefStrings.MODID, "textures/models/core_receiver.png"); public static final ResourceLocation dfc_injector_tex = new ResourceLocation(RefStrings.MODID, "textures/models/core_injector.png"); public static final ResourceLocation dfc_stabilizer_tex = new ResourceLocation(RefStrings.MODID, "textures/models/core_stabilizer.png"); //Radgen public static final ResourceLocation radgen_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/radgen.png"); //Small Reactor public static final ResourceLocation reactor_small_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/reactor_small_base.png"); public static final ResourceLocation reactor_small_rods_tex = new ResourceLocation(RefStrings.MODID, "textures/models/reactor_small_rods.png"); //Breeder public static final ResourceLocation breeder_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/breeder.png"); //ITER public static final ResourceLocation iter_glass = new ResourceLocation(RefStrings.MODID, "textures/models/iter/glass.png"); public static final ResourceLocation iter_microwave = new ResourceLocation(RefStrings.MODID, "textures/models/iter/microwave.png"); public static final ResourceLocation iter_motor = new ResourceLocation(RefStrings.MODID, "textures/models/iter/motor.png"); public static final ResourceLocation iter_plasma = new ResourceLocation(RefStrings.MODID, "textures/models/iter/plasma.png"); public static final ResourceLocation iter_rails = new ResourceLocation(RefStrings.MODID, "textures/models/iter/rails.png"); public static final ResourceLocation iter_solenoid = new ResourceLocation(RefStrings.MODID, "textures/models/iter/solenoid.png"); public static final ResourceLocation iter_toroidal = new ResourceLocation(RefStrings.MODID, "textures/models/iter/toroidal.png"); public static final ResourceLocation iter_torus = new ResourceLocation(RefStrings.MODID, "textures/models/iter/torus.png"); public static final ResourceLocation iter_torus_tungsten = new ResourceLocation(RefStrings.MODID, "textures/models/iter/torus_tungsten.png"); public static final ResourceLocation iter_torus_desh = new ResourceLocation(RefStrings.MODID, "textures/models/iter/torus_desh.png"); public static final ResourceLocation iter_torus_chlorophyte = new ResourceLocation(RefStrings.MODID, "textures/models/iter/torus_chlorophyte.png"); public static final ResourceLocation iter_torus_vaporwave = new ResourceLocation(RefStrings.MODID, "textures/models/iter/torus_vaporwave.png"); //Watz public static final ResourceLocation watz_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/watz.png"); //FENSU public static final ResourceLocation fensu_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/fensu.png"); //Radar public static final ResourceLocation radar_body_tex = new ResourceLocation(RefStrings.MODID, "textures/models/radar_base.png"); public static final ResourceLocation radar_head_tex = new ResourceLocation(RefStrings.MODID, "textures/models/radar_head.png"); public static final ResourceLocation radar_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/radar_base.png"); public static final ResourceLocation radar_dish_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/radar_dish.png"); //Forcefield public static final ResourceLocation forcefield_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/forcefield_base.png"); public static final ResourceLocation forcefield_top_tex = new ResourceLocation(RefStrings.MODID, "textures/models/forcefield_top.png"); //Shredder public static final ResourceLocation shredder_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/shredder.png"); //Bombs public static final ResourceLocation bomb_gadget_tex = new ResourceLocation(RefStrings.MODID, "textures/models/TheGadget3_tex.png"); public static final ResourceLocation bomb_boy_tex = new ResourceLocation(RefStrings.MODID, "textures/models/lilboy.png"); public static final ResourceLocation bomb_man_tex = new ResourceLocation(RefStrings.MODID, "textures/models/FatMan.png"); public static final ResourceLocation bomb_mike_tex = new ResourceLocation(RefStrings.MODID, "textures/models/IvyMike.png"); public static final ResourceLocation bomb_tsar_tex = new ResourceLocation(RefStrings.MODID, "textures/models/TsarBomba.png"); public static final ResourceLocation bomb_prototype_tex = new ResourceLocation(RefStrings.MODID, "textures/models/Prototype.png"); public static final ResourceLocation bomb_fleija_tex = new ResourceLocation(RefStrings.MODID, "textures/models/Fleija.png"); public static final ResourceLocation bomb_solinium_tex = new ResourceLocation(RefStrings.MODID, "textures/models/bombs/ufp.png"); public static final ResourceLocation n2_tex = new ResourceLocation(RefStrings.MODID, "textures/models/bombs/n2.png"); public static final ResourceLocation bomb_custom_tex = new ResourceLocation(RefStrings.MODID, "textures/models/CustomNuke.png"); public static final ResourceLocation bomb_multi_tex = new ResourceLocation(RefStrings.MODID, "textures/models/BombGeneric.png"); public static final ResourceLocation n45_globe_tex = new ResourceLocation(RefStrings.MODID, "textures/models/bombs/n45_globe.png"); public static final ResourceLocation n45_knob_tex = new ResourceLocation(RefStrings.MODID, "textures/models/bombs/n45_knob.png"); public static final ResourceLocation n45_rod_tex = new ResourceLocation(RefStrings.MODID, "textures/models/bombs/n45_rod.png"); public static final ResourceLocation n45_stand_tex = new ResourceLocation(RefStrings.MODID, "textures/models/n45_stand.png"); public static final ResourceLocation n45_chain_tex = new ResourceLocation(RefStrings.MODID, "textures/models/bombs/n45_chain.png"); public static final ResourceLocation fstbmb_tex = new ResourceLocation(RefStrings.MODID, "textures/models/bombs/fstbmb.png"); public static final ResourceLocation dud_tex = new ResourceLocation(RefStrings.MODID, "textures/models/BalefireCrashed.png"); //Satellites public static final ResourceLocation sat_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/sat_base.png"); public static final ResourceLocation sat_radar_tex = new ResourceLocation(RefStrings.MODID, "textures/models/sat_radar.png"); public static final ResourceLocation sat_resonator_tex = new ResourceLocation(RefStrings.MODID, "textures/models/sat_resonator.png"); public static final ResourceLocation sat_scanner_tex = new ResourceLocation(RefStrings.MODID, "textures/models/sat_scanner.png"); public static final ResourceLocation sat_mapper_tex = new ResourceLocation(RefStrings.MODID, "textures/models/sat_mapper.png"); public static final ResourceLocation sat_laser_tex = new ResourceLocation(RefStrings.MODID, "textures/models/sat_laser.png"); public static final ResourceLocation sat_foeq_tex = new ResourceLocation(RefStrings.MODID, "textures/models/sat_foeq.png"); public static final ResourceLocation sat_foeq_burning_tex = new ResourceLocation(RefStrings.MODID, "textures/models/sat_foeq_burning.png"); //SatDock public static final ResourceLocation satdock_tex = new ResourceLocation(RefStrings.MODID, "textures/models/sat_dock.png"); //Vault Door public static final ResourceLocation vault_cog_tex = new ResourceLocation(RefStrings.MODID, "textures/models/vault_cog.png"); public static final ResourceLocation vault_frame_tex = new ResourceLocation(RefStrings.MODID, "textures/models/vault_frame.png"); public static final ResourceLocation vault_label_101_tex = new ResourceLocation(RefStrings.MODID, "textures/models/vault_label_101.png"); public static final ResourceLocation vault_label_87_tex = new ResourceLocation(RefStrings.MODID, "textures/models/vault_label_87.png"); public static final ResourceLocation vault_label_106_tex = new ResourceLocation(RefStrings.MODID, "textures/models/vault_label_106.png"); public static final ResourceLocation stable_cog_tex = new ResourceLocation(RefStrings.MODID, "textures/models/stable_cog.png"); public static final ResourceLocation stable_label_tex = new ResourceLocation(RefStrings.MODID, "textures/models/stable_label.png"); public static final ResourceLocation stable_label_99_tex = new ResourceLocation(RefStrings.MODID, "textures/models/stable_label_99.png"); public static final ResourceLocation vault4_cog_tex = new ResourceLocation(RefStrings.MODID, "textures/models/vault4_cog.png"); public static final ResourceLocation vault4_label_111_tex = new ResourceLocation(RefStrings.MODID, "textures/models/vault4_label_111.png"); public static final ResourceLocation vault4_label_81_tex = new ResourceLocation(RefStrings.MODID, "textures/models/vault4_label_81.png"); //Solar Tower public static final ResourceLocation solar_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/solar_boiler.png"); public static final ResourceLocation solar_mirror_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/solar_mirror.png"); //Blast Door public static final ResourceLocation blast_door_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/blast_door_base.png"); public static final ResourceLocation blast_door_tooth_tex = new ResourceLocation(RefStrings.MODID, "textures/models/blast_door_tooth.png"); public static final ResourceLocation blast_door_slider_tex = new ResourceLocation(RefStrings.MODID, "textures/models/blast_door_slider.png"); public static final ResourceLocation blast_door_block_tex = new ResourceLocation(RefStrings.MODID, "textures/models/blast_door_block.png"); //Doors public static final ResourceLocation transition_seal_tex = new ResourceLocation(RefStrings.MODID, "textures/models/doors/transition_seal.png"); public static final ResourceLocation fire_door_tex = new ResourceLocation(RefStrings.MODID, "textures/models/doors/fire_door.png"); //Tesla Coil public static final ResourceLocation tesla_tex = new ResourceLocation(RefStrings.MODID, "textures/models/tesla.png"); public static final ResourceLocation teslacrab_tex = new ResourceLocation(RefStrings.MODID, "textures/entity/teslacrab.png"); public static final ResourceLocation taintcrab_tex = new ResourceLocation(RefStrings.MODID, "textures/entity/taintcrab.png"); public static final ResourceLocation maskman_tex = new ResourceLocation(RefStrings.MODID, "textures/entity/maskman.png"); public static final ResourceLocation iou = new ResourceLocation(RefStrings.MODID, "textures/entity/iou.png"); public static final ResourceLocation spider_tex = new ResourceLocation(RefStrings.MODID, "textures/entity/blockspider.png"); public static final ResourceLocation ufo_tex = new ResourceLocation(RefStrings.MODID, "textures/entity/ufo.png"); //ZIRNOX public static final ResourceLocation zirnox_tex = new ResourceLocation(RefStrings.MODID, "textures/models/zirnox.png"); public static final ResourceLocation zirnox_destroyed_tex = new ResourceLocation(RefStrings.MODID, "textures/models/zirnox_destroyed.png"); //Electricity public static final ResourceLocation connector_tex = new ResourceLocation(RefStrings.MODID, "textures/models/network/connector.png"); public static final ResourceLocation pylon_large_tex = new ResourceLocation(RefStrings.MODID, "textures/models/network/pylon_large.png"); public static final ResourceLocation substation_tex = new ResourceLocation(RefStrings.MODID, "textures/models/network/substation.png"); //Radiolysis public static final ResourceLocation radiolysis_tex = new ResourceLocation(RefStrings.MODID, "textures/models/radiolysis.png"); //Electrolyser public static final ResourceLocation electrolyser_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/electrolyser.png"); //Charger public static final ResourceLocation charger_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/charger.png"); //DecoContainer public static final ResourceLocation file_cabinet_tex = new ResourceLocation(RefStrings.MODID, "textures/models/file_cabinet.png"); public static final ResourceLocation file_cabinet_steel_tex = new ResourceLocation(RefStrings.MODID, "textures/models/file_cabinet_steel.png"); ////Obj Items //Shimmer Sledge public static final IModelCustom shimmer_sledge = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/shimmer_sledge.obj")); public static final IModelCustom shimmer_axe = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/shimmer_axe.obj")); public static final IModelCustom stopsign = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/weapons/stopsign.obj")); public static final IModelCustom pch = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/pch.obj")); public static final IModelCustom gavel = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/gavel.obj")); public static final IModelCustom crucible = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/crucible.obj")); public static final IModelCustom chainsaw = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/chainsaw.obj"), false); public static final IModelCustom brimstone = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/brimstone.obj")); public static final IModelCustom hk69 = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/hk69.obj")); public static final IModelCustom deagle = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/deagle.obj")); public static final IModelCustom shotty = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/supershotty.obj")); public static final IModelCustom ks23 = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/ks23.obj")); public static final IModelCustom flamer = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/flamer.obj")); public static final IModelCustom flechette = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/flechette.obj")); public static final IModelCustom quadro = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/quadro.obj")); public static final IModelCustom sauergun = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/sauergun.obj")); public static final IModelCustom vortex = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/vortex.obj")); public static final IModelCustom thompson = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/thompson.obj")); public static final IModelCustom bolter = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/bolter.obj")); public static final IModelCustom ff_python = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/python.obj")); public static final IModelCustom ff_maresleg = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/maresleg.obj")); public static final IModelCustom ff_nightmare = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/nightmare.obj")); public static final IModelCustom fireext = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/fireext.obj")); public static final IModelCustom ar15 = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/ar15.obj")); public static final IModelCustom stinger = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/stinger.obj")); public static final IModelCustom mg42 = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/mg42.obj")); public static final IModelCustom rem700 = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/rem700.obj")); public static final IModelCustom rem700poly = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/rem700poly.obj")); public static final IModelCustom rem700sat = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/rem700sat.obj")); public static final IModelCustom cursed_revolver = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/cursed.obj")); public static final IModelCustom detonator_laser = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/detonator_laser.obj")); public static final IModelCustom spas_12 = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/spas-12.obj")); public static final IModelCustom nightmare_dark = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/nightmare_dark.obj")); public static final IModelCustom glass_cannon = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/glass_cannon.obj")); public static final IModelCustom folly = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/folly.obj")); public static final IModelCustom bio_revolver = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/bio_revolver.obj")); public static final IModelCustom chemthrower = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/chemthrower.obj")).asDisplayList(); public static final IModelCustom lance = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/lance.obj")); public static final IModelCustom grenade_frag = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/grenade_frag.obj")); public static final IModelCustom grenade_aschrab = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/weapons/grenade_aschrab.obj")); public static final IModelCustom armor_bj = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/BJ.obj")); public static final IModelCustom armor_hev = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/hev.obj")); public static final IModelCustom armor_ajr = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/AJR.obj")); public static final IModelCustom armor_hat = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/hat.obj")); public static final IModelCustom armor_goggles = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/goggles.obj")); public static final IModelCustom armor_fau = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/fau.obj")); public static final IModelCustom armor_dnt = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/dnt.obj")); public static final IModelCustom armor_steamsuit = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/steamsuit.obj")); public static final IModelCustom armor_dieselsuit = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/bnuuy.obj")); public static final IModelCustom armor_remnant = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/remnant.obj")); public static final IModelCustom armor_bismuth = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/bismuth.obj")); public static final IModelCustom armor_mod_tesla = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/mod_tesla.obj")); public static final IModelCustom armor_wings = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/murk.obj")); public static final IModelCustom armor_solstice = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/armor/solstice.obj")); public static final IModelCustom player_manly_af = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/armor/player_fem.obj")); ////Texture Items //Shimmer Sledge public static final ResourceLocation shimmer_sledge_tex = new ResourceLocation(RefStrings.MODID, "textures/models/shimmer_sledge.png"); public static final ResourceLocation shimmer_axe_tex = new ResourceLocation(RefStrings.MODID, "textures/models/shimmer_axe.png"); public static final ResourceLocation stopsign_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/stopsign.png"); public static final ResourceLocation sopsign_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/sopsign.png"); public static final ResourceLocation chernobylsign_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/chernobylsign.png"); public static final ResourceLocation pch_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/pch.png"); public static final ResourceLocation gavel_wood = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/gavel_wood.png"); public static final ResourceLocation gavel_lead = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/gavel_lead.png"); public static final ResourceLocation gavel_diamond = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/gavel_diamond.png"); public static final ResourceLocation gavel_mese = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/gavel_mese.png"); public static final ResourceLocation crucible_hilt = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/crucible_hilt.png"); public static final ResourceLocation crucible_guard = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/crucible_guard.png"); public static final ResourceLocation crucible_blade = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/crucible_blade.png"); public static final ResourceLocation chainsaw_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/chainsaw.png"); public static final ResourceLocation brimstone_tex = new ResourceLocation(RefStrings.MODID, "textures/models/brimstone.png"); public static final ResourceLocation hk69_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/hk69.png"); public static final ResourceLocation deagle_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/deagle.png"); public static final ResourceLocation ks23_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ks23.png"); public static final ResourceLocation shotty_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/shotty.png"); public static final ResourceLocation flamer_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flamer.png"); public static final ResourceLocation flechette_body = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_body.png"); public static final ResourceLocation flechette_barrel = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_barrel.png"); public static final ResourceLocation flechette_gren_tube = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_gren_tube.png"); public static final ResourceLocation flechette_grenades = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_grenades.png"); public static final ResourceLocation flechette_pivot = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_pivot.png"); public static final ResourceLocation flechette_top = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_top.png"); public static final ResourceLocation flechette_chamber = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_chamber.png"); public static final ResourceLocation flechette_base = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_base.png"); public static final ResourceLocation flechette_drum = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_drum.png"); public static final ResourceLocation flechette_trigger = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_trigger.png"); public static final ResourceLocation flechette_stock = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/flechette_stock.png"); public static final ResourceLocation quadro_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/quadro.png"); public static final ResourceLocation quadro_rocket_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/quadro_rocket.png"); public static final ResourceLocation sauergun_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/sauergun.png"); public static final ResourceLocation vortex_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/vortex.png"); public static final ResourceLocation thompson_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/thompson.png"); public static final ResourceLocation bolter_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/bolter.png"); public static final ResourceLocation bolter_digamma_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/bolter_digamma.png"); public static final ResourceLocation fireext_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/fireext_normal.png"); public static final ResourceLocation fireext_foam_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/fireext_foam.png"); public static final ResourceLocation fireext_sand_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/fireext_sand.png"); public static final ResourceLocation ar15_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/carbine.png"); public static final ResourceLocation stinger_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/stinger.png"); public static final ResourceLocation sky_stinger_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/sky_stinger.png"); public static final ResourceLocation mg42_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/mg42.png"); public static final ResourceLocation rem700_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/rem700.png"); public static final ResourceLocation rem700poly_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/rem700poly.png"); public static final ResourceLocation rem700sat_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/rem700sat.png"); public static final ResourceLocation detonator_laser_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/detonator_laser.png"); public static final ResourceLocation spas_12_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/spas-12.png"); public static final ResourceLocation glass_cannon_panel_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/glass_cannon_panel.png"); public static final ResourceLocation folly_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/folly.png"); public static final ResourceLocation bio_revolver_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/bio_revolver.png"); public static final ResourceLocation chemthrower_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/chemthrower.png"); public static final ResourceLocation lance_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/lance.png"); public static final ResourceLocation ff_gold = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/gold.png"); public static final ResourceLocation ff_gun_bright = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/gun_bright.png"); public static final ResourceLocation ff_gun_dark = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/gun_dark.png"); public static final ResourceLocation ff_gun_normal = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/gun_normal.png"); public static final ResourceLocation ff_iron = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/iron.png"); public static final ResourceLocation ff_lead = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/lead.png"); public static final ResourceLocation ff_saturnite = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/saturnite.png"); public static final ResourceLocation ff_schrabidium = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/schrabidium.png"); public static final ResourceLocation ff_wood = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/wood.png"); public static final ResourceLocation ff_wood_red = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/wood_red.png"); public static final ResourceLocation ff_cursed = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/cursed.png"); public static final ResourceLocation ff_nightmare_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/nightmare.png"); public static final ResourceLocation ff_nightmare_orig_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/ff/nightmare_orig.png"); public static final ResourceLocation grenade_mk2 = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/grenade_mk2.png"); public static final ResourceLocation grenade_aschrab_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/grenade_aschrab.png"); public static final ResourceLocation bj_eyepatch = new ResourceLocation(RefStrings.MODID, "textures/armor/bj_eyepatch.png"); public static final ResourceLocation bj_leg = new ResourceLocation(RefStrings.MODID, "textures/armor/bj_leg.png"); public static final ResourceLocation bj_chest = new ResourceLocation(RefStrings.MODID, "textures/armor/bj_chest.png"); public static final ResourceLocation bj_jetpack = new ResourceLocation(RefStrings.MODID, "textures/armor/bj_jetpack.png"); public static final ResourceLocation bj_arm = new ResourceLocation(RefStrings.MODID, "textures/armor/bj_arm.png"); public static final ResourceLocation hev_helmet = new ResourceLocation(RefStrings.MODID, "textures/armor/hev_helmet.png"); public static final ResourceLocation hev_leg = new ResourceLocation(RefStrings.MODID, "textures/armor/hev_leg.png"); public static final ResourceLocation hev_chest = new ResourceLocation(RefStrings.MODID, "textures/armor/hev_chest.png"); public static final ResourceLocation hev_arm = new ResourceLocation(RefStrings.MODID, "textures/armor/hev_arm.png"); public static final ResourceLocation ajr_helmet = new ResourceLocation(RefStrings.MODID, "textures/armor/ajr_helmet.png"); public static final ResourceLocation ajr_leg = new ResourceLocation(RefStrings.MODID, "textures/armor/ajr_leg.png"); public static final ResourceLocation ajr_chest = new ResourceLocation(RefStrings.MODID, "textures/armor/ajr_chest.png"); public static final ResourceLocation ajr_arm = new ResourceLocation(RefStrings.MODID, "textures/armor/ajr_arm.png"); public static final ResourceLocation ajro_helmet = new ResourceLocation(RefStrings.MODID, "textures/armor/ajro_helmet.png"); public static final ResourceLocation ajro_leg = new ResourceLocation(RefStrings.MODID, "textures/armor/ajro_leg.png"); public static final ResourceLocation ajro_chest = new ResourceLocation(RefStrings.MODID, "textures/armor/ajro_chest.png"); public static final ResourceLocation ajro_arm = new ResourceLocation(RefStrings.MODID, "textures/armor/ajro_arm.png"); public static final ResourceLocation fau_helmet = new ResourceLocation(RefStrings.MODID, "textures/armor/fau_helmet.png"); public static final ResourceLocation fau_leg = new ResourceLocation(RefStrings.MODID, "textures/armor/fau_leg.png"); public static final ResourceLocation fau_chest = new ResourceLocation(RefStrings.MODID, "textures/armor/fau_chest.png"); public static final ResourceLocation fau_cassette = new ResourceLocation(RefStrings.MODID, "textures/armor/fau_cassette.png"); public static final ResourceLocation fau_arm = new ResourceLocation(RefStrings.MODID, "textures/armor/fau_arm.png"); public static final ResourceLocation dnt_helmet = new ResourceLocation(RefStrings.MODID, "textures/armor/dnt_helmet.png"); public static final ResourceLocation dnt_leg = new ResourceLocation(RefStrings.MODID, "textures/armor/dnt_leg.png"); public static final ResourceLocation dnt_chest = new ResourceLocation(RefStrings.MODID, "textures/armor/dnt_chest.png"); public static final ResourceLocation dnt_arm = new ResourceLocation(RefStrings.MODID, "textures/armor/dnt_arm.png"); public static final ResourceLocation steamsuit_helmet = new ResourceLocation(RefStrings.MODID, "textures/armor/steamsuit_helmet.png"); public static final ResourceLocation steamsuit_leg = new ResourceLocation(RefStrings.MODID, "textures/armor/steamsuit_leg.png"); public static final ResourceLocation steamsuit_chest = new ResourceLocation(RefStrings.MODID, "textures/armor/steamsuit_chest.png"); public static final ResourceLocation steamsuit_arm = new ResourceLocation(RefStrings.MODID, "textures/armor/steamsuit_arm.png"); public static final ResourceLocation dieselsuit_helmet = new ResourceLocation(RefStrings.MODID, "textures/armor/bnuuy_helmet.png"); public static final ResourceLocation dieselsuit_leg = new ResourceLocation(RefStrings.MODID, "textures/armor/bnuuy_leg.png"); public static final ResourceLocation dieselsuit_chest = new ResourceLocation(RefStrings.MODID, "textures/armor/bnuuy_chest.png"); public static final ResourceLocation dieselsuit_arm = new ResourceLocation(RefStrings.MODID, "textures/armor/bnuuy_arm.png"); public static final ResourceLocation rpa_helmet = new ResourceLocation(RefStrings.MODID, "textures/armor/rpa_helmet.png"); public static final ResourceLocation rpa_leg = new ResourceLocation(RefStrings.MODID, "textures/armor/rpa_leg.png"); public static final ResourceLocation rpa_chest = new ResourceLocation(RefStrings.MODID, "textures/armor/rpa_chest.png"); public static final ResourceLocation rpa_arm = new ResourceLocation(RefStrings.MODID, "textures/armor/rpa_arm.png"); public static final ResourceLocation mod_tesla = new ResourceLocation(RefStrings.MODID, "textures/armor/mod_tesla.png"); public static final ResourceLocation armor_bismuth_tex = new ResourceLocation(RefStrings.MODID, "textures/armor/bismuth.png"); public static final ResourceLocation wings_murk = new ResourceLocation(RefStrings.MODID, "textures/armor/wings_murk.png"); public static final ResourceLocation wings_bob = new ResourceLocation(RefStrings.MODID, "textures/armor/wings_bob.png"); public static final ResourceLocation wings_black = new ResourceLocation(RefStrings.MODID, "textures/armor/wings_black.png"); public static final ResourceLocation wings_solstice = new ResourceLocation(RefStrings.MODID, "textures/armor/wings_solstice.png"); public static final ResourceLocation hat = new ResourceLocation(RefStrings.MODID, "textures/armor/hat.png"); public static final ResourceLocation goggles = new ResourceLocation(RefStrings.MODID, "textures/armor/goggles.png"); public static final ResourceLocation player_manly_tex = new ResourceLocation(RefStrings.MODID, "textures/entity/player_fem.png"); ////Obj Entities //Boxcar public static final IModelCustom boxcar = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/boxcar.obj")); public static final IModelCustom duchessgambit = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/duchessgambit.obj")); public static final IModelCustom building = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/weapons/building.obj")); public static final IModelCustom rpc = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/rpc.obj")); public static final IModelCustom tom_main = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/weapons/tom_main.obj")); public static final IModelCustom tom_flame = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/weapons/tom_flame.hmf")); public static final IModelCustom nikonium = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/nikonium.obj")); //Projectiles public static final IModelCustom projectiles = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/projectiles/projectiles.obj")); //Bomber public static final IModelCustom dornier = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/dornier.obj")); public static final IModelCustom b29 = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/b29.obj")); //Missiles public static final IModelCustom missileV2 = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileV2.obj")); public static final IModelCustom missileStrong = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileGeneric.obj")); public static final IModelCustom missileHuge = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileHuge.obj")); public static final IModelCustom missileNuclear = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileNeon.obj")); public static final IModelCustom missileMIRV = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileMIRV.obj")); public static final IModelCustom missileThermo = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileThermo.obj")); public static final IModelCustom missileDoomsday = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileDoomsday.obj")); public static final IModelCustom missileTaint = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileTaint.obj")); public static final IModelCustom missileShuttle = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileShuttle.obj")); public static final IModelCustom missileCarrier = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileCarrier.obj")); public static final IModelCustom missileBooster = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missileBooster.obj")); public static final IModelCustom minerRocket = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/minerRocket.obj")); public static final IModelCustom soyuz = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/soyuz.obj")); public static final IModelCustom soyuz_lander = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/soyuz_lander.obj")); public static final IModelCustom soyuz_module = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/soyuz_module.obj")); public static final IModelCustom soyuz_launcher_legs = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/soyuz_launcher_legs.obj")); public static final IModelCustom soyuz_launcher_table = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/soyuz_launcher_table.obj")); public static final IModelCustom soyuz_launcher_tower_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/soyuz_launcher_tower_base.obj")); public static final IModelCustom soyuz_launcher_tower = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/soyuz_launcher_tower.obj")); public static final IModelCustom soyuz_launcher_support_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/soyuz_launcher_support_base.obj")); public static final IModelCustom soyuz_launcher_support = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/soyuz_launcher_support.obj")); //Missile Parts public static final IModelCustom missile_pad = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missilePad.obj")); public static final IModelCustom missile_assembly = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_assembly.obj")); public static final IModelCustom strut = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/strut.obj")); public static final IModelCustom compact_launcher = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/compact_launcher.obj")); public static final IModelCustom launch_table_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/launch_table_base.obj")); public static final IModelCustom launch_table_large_pad = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/launch_table_large_pad.obj")); public static final IModelCustom launch_table_small_pad = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/launch_table_small_pad.obj")); public static final IModelCustom launch_table_large_scaffold_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/launch_table_large_scaffold_base.obj")); public static final IModelCustom launch_table_large_scaffold_connector = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/launch_table_large_scaffold_connector.obj")); public static final IModelCustom launch_table_large_scaffold_empty = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/launch_table_large_scaffold_empty.obj")); public static final IModelCustom launch_table_small_scaffold_base = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/launch_table_small_scaffold_base.obj")); public static final IModelCustom launch_table_small_scaffold_connector = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/launch_table_small_scaffold_connector.obj")); public static final IModelCustom launch_table_small_scaffold_empty = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/launch_table/launch_table_small_scaffold_empty.obj")); public static final IModelCustom mp_t_10_kerosene = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_10_kerosene.obj")); public static final IModelCustom mp_t_10_kerosene_tec = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_10_kerosene_tec.obj")); public static final IModelCustom mp_t_10_solid = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_10_solid.obj")); public static final IModelCustom mp_t_10_xenon = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_10_xenon.obj")); public static final IModelCustom mp_t_15_kerosene = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_15_kerosene.obj")); public static final IModelCustom mp_t_15_kerosene_tec = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_15_kerosene_tec.obj")); public static final IModelCustom mp_t_15_kerosene_dual = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_15_kerosene_dual.obj")); public static final IModelCustom mp_t_15_kerosene_triple = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_15_kerosene_triple.obj")); public static final IModelCustom mp_t_15_solid = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_15_solid.obj")); public static final IModelCustom mp_t_15_solid_hexdecuple = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_15_solid_hexdecuple.obj")); public static final IModelCustom mp_t_15_balefire_short = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_15_balefire_short.obj")); public static final IModelCustom mp_t_15_balefire = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_15_balefire.obj")); public static final IModelCustom mp_t_15_balefire_large = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_15_balefire_large.obj")); public static final IModelCustom mp_t_20_kerosene = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_20_kerosene.obj")); public static final IModelCustom mp_t_20_kerosene_dual = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_20_kerosene_dual.obj")); public static final IModelCustom mp_t_20_kerosene_triple = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_20_kerosene_triple.obj")); public static final IModelCustom mp_t_20_solid = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_20_solid.obj")); public static final IModelCustom mp_t_20_solid_multi = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_t_20_solid_multi.obj")); public static final IModelCustom mp_s_10_flat = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_s_10_flat.obj")); public static final IModelCustom mp_s_10_cruise = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_s_10_cruise.obj")); public static final IModelCustom mp_s_10_space = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_s_10_space.obj")); public static final IModelCustom mp_s_15_flat = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_s_15_flat.obj")); public static final IModelCustom mp_s_15_thin = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_s_15_thin.obj")); public static final IModelCustom mp_s_15_soyuz = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_s_15_soyuz.obj")); public static final IModelCustom mp_s_20 = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_s_20.obj")); public static final IModelCustom mp_f_10_kerosene = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_f_10_kerosene.obj")); public static final IModelCustom mp_f_10_long_kerosene = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_f_10_long_kerosene.obj")); public static final IModelCustom mp_f_10_15_kerosene = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_f_10_15_kerosene.obj")); public static final IModelCustom mp_f_15_kerosene = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_f_15_kerosene.obj")); public static final IModelCustom mp_f_15_hydrogen = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_f_15_hydrogen.obj")); public static final IModelCustom mp_f_15_20_kerosene = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_f_15_20_kerosene.obj")); public static final IModelCustom mp_f_20 = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_f_20.obj")); public static final IModelCustom mp_w_10_he = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_10_he.obj")); public static final IModelCustom mp_w_10_incendiary = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_10_incendiary.obj")); public static final IModelCustom mp_w_10_buster = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_10_buster.obj")); public static final IModelCustom mp_w_10_nuclear = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_10_nuclear.obj")); public static final IModelCustom mp_w_10_nuclear_large = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_10_nuclear_large.obj")); public static final IModelCustom mp_w_10_taint = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_10_taint.obj")); public static final IModelCustom mp_w_15_he = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_15_he.obj")); public static final IModelCustom mp_w_15_incendiary = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_15_incendiary.obj")); public static final IModelCustom mp_w_15_nuclear = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_15_nuclear.obj")); public static final IModelCustom mp_w_15_boxcar = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_15_boxcar.obj")); public static final IModelCustom mp_w_15_n2 = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_15_n2.obj")); public static final IModelCustom mp_w_15_balefire = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_15_balefire.obj")); public static final IModelCustom mp_w_15_mirv = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_15_mirv.obj")); public static final IModelCustom mp_w_15_turbine = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_15_turbine.obj")); public static final IModelCustom mp_w_20 = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/missile_parts/mp_w_20.obj")); //Carts public static final IModelCustom cart = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/vehicles/cart.obj")); public static final IModelCustom cart_destroyer = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/vehicles/cart_destroyer.obj")); public static final IModelCustom cart_powder = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/vehicles/cart_powder.obj")); ////Texture Entities //Blast public static final ResourceLocation fireball = new ResourceLocation(RefStrings.MODID, "textures/models/explosion/fireball.png"); public static final ResourceLocation balefire = new ResourceLocation(RefStrings.MODID, "textures/models/explosion/balefire.png"); public static final ResourceLocation tomblast = new ResourceLocation(RefStrings.MODID, "textures/models/explosion/tomblast.png"); public static final ResourceLocation dust = new ResourceLocation(RefStrings.MODID, "textures/models/explosion/dust.png"); //Boxcar public static final ResourceLocation boxcar_tex = new ResourceLocation(RefStrings.MODID, "textures/models/boxcar.png"); public static final ResourceLocation duchessgambit_tex = new ResourceLocation(RefStrings.MODID, "textures/models/duchessgambit.png"); public static final ResourceLocation building_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/building.png"); public static final ResourceLocation rpc_tex = new ResourceLocation(RefStrings.MODID, "textures/models/rpc.png"); public static final ResourceLocation tom_main_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/tom_main.png"); public static final ResourceLocation tom_flame_tex = new ResourceLocation(RefStrings.MODID, "textures/models/weapons/tom_flame.png"); public static final ResourceLocation nikonium_tex = new ResourceLocation(RefStrings.MODID, "textures/models/misc/nikonium.png"); //Projectiles public static final ResourceLocation bullet_pistol_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/bullet_pistol.png"); public static final ResourceLocation bullet_rifle_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/bullet_rifle.png"); public static final ResourceLocation buckshot_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/pellet_buckshot.png"); public static final ResourceLocation flechette_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/flechette.png"); public static final ResourceLocation grenade_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/grenade.png"); public static final ResourceLocation rocket_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/rocket.png"); public static final ResourceLocation rocket_mirv_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/rocket_mirv.png"); public static final ResourceLocation mini_nuke_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/mini_nuke.png"); public static final ResourceLocation mini_mirv_tex = new ResourceLocation(RefStrings.MODID, "textures/models/projectiles/mini_mirv.png"); //Bomber public static final ResourceLocation dornier_0_tex = new ResourceLocation(RefStrings.MODID, "textures/models/dornier_0.png"); public static final ResourceLocation dornier_1_tex = new ResourceLocation(RefStrings.MODID, "textures/models/dornier_1.png"); public static final ResourceLocation dornier_2_tex = new ResourceLocation(RefStrings.MODID, "textures/models/dornier_2.png"); public static final ResourceLocation dornier_3_tex = new ResourceLocation(RefStrings.MODID, "textures/models/dornier_3.png"); public static final ResourceLocation dornier_4_tex = new ResourceLocation(RefStrings.MODID, "textures/models/dornier_4.png"); public static final ResourceLocation b29_0_tex = new ResourceLocation(RefStrings.MODID, "textures/models/b29_0.png"); public static final ResourceLocation b29_1_tex = new ResourceLocation(RefStrings.MODID, "textures/models/b29_1.png"); public static final ResourceLocation b29_2_tex = new ResourceLocation(RefStrings.MODID, "textures/models/b29_2.png"); public static final ResourceLocation b29_3_tex = new ResourceLocation(RefStrings.MODID, "textures/models/b29_3.png"); //Missiles public static final ResourceLocation missileV2_HE_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileV2_HE.png"); public static final ResourceLocation missileV2_IN_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileV2_IN.png"); public static final ResourceLocation missileV2_CL_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileV2_CL.png"); public static final ResourceLocation missileV2_BU_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileV2_BU.png"); public static final ResourceLocation missileAA_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileAA.png"); public static final ResourceLocation missileStrong_HE_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileStrong_HE.png"); public static final ResourceLocation missileStrong_EMP_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileStrong_EMP.png"); public static final ResourceLocation missileStrong_IN_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileStrong_IN.png"); public static final ResourceLocation missileStrong_CL_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileStrong_CL.png"); public static final ResourceLocation missileStrong_BU_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileStrong_BU.png"); public static final ResourceLocation missileHuge_HE_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileHuge_HE.png"); public static final ResourceLocation missileHuge_IN_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileHuge_IN.png"); public static final ResourceLocation missileHuge_CL_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileHuge_CL.png"); public static final ResourceLocation missileHuge_BU_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileHuge_BU.png"); public static final ResourceLocation missileNuclear_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileNeon.png"); public static final ResourceLocation missileMIRV_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileNeonH.png"); public static final ResourceLocation missileVolcano_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileNeonV.png"); public static final ResourceLocation missileEndo_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileEndo.png"); public static final ResourceLocation missileExo_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileExo.png"); public static final ResourceLocation missileDoomsday_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileDoomsday.png"); public static final ResourceLocation missileTaint_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileTaint.png"); public static final ResourceLocation missileShuttle_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileShuttle.png"); public static final ResourceLocation missileMicro_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileMicro.png"); public static final ResourceLocation missileCarrier_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileCarrier.png"); public static final ResourceLocation missileBooster_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileBooster.png"); public static final ResourceLocation minerRocket_tex = new ResourceLocation(RefStrings.MODID, "textures/models/minerRocket.png"); public static final ResourceLocation bobmazon_tex = new ResourceLocation(RefStrings.MODID, "textures/models/bobmazon.png"); public static final ResourceLocation siege_dropship_tex = new ResourceLocation(RefStrings.MODID, "textures/models/siege_dropship.png"); public static final ResourceLocation missileMicroBHole_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileMicroBHole.png"); public static final ResourceLocation missileMicroSchrab_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileMicroSchrab.png"); public static final ResourceLocation missileMicroEMP_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missileMicroEMP.png"); public static final ResourceLocation soyuz_engineblock = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/engineblock.png"); public static final ResourceLocation soyuz_bottomstage = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/bottomstage.png"); public static final ResourceLocation soyuz_topstage = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/topstage.png"); public static final ResourceLocation soyuz_payload = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/payload.png"); public static final ResourceLocation soyuz_payloadblocks = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/payloadblocks.png"); public static final ResourceLocation soyuz_les = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/les.png"); public static final ResourceLocation soyuz_lesthrusters = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/lesthrusters.png"); public static final ResourceLocation soyuz_mainengines = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/mainengines.png"); public static final ResourceLocation soyuz_sideengines = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/sideengines.png"); public static final ResourceLocation soyuz_booster = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/booster.png"); public static final ResourceLocation soyuz_boosterside = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz/boosterside.png"); public static final ResourceLocation soyuz_luna_engineblock = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/engineblock.png"); public static final ResourceLocation soyuz_luna_bottomstage = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/bottomstage.png"); public static final ResourceLocation soyuz_luna_topstage = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/topstage.png"); public static final ResourceLocation soyuz_luna_payload = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/payload.png"); public static final ResourceLocation soyuz_luna_payloadblocks = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/payloadblocks.png"); public static final ResourceLocation soyuz_luna_les = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/les.png"); public static final ResourceLocation soyuz_luna_lesthrusters = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/lesthrusters.png"); public static final ResourceLocation soyuz_luna_mainengines = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/mainengines.png"); public static final ResourceLocation soyuz_luna_sideengines = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/sideengines.png"); public static final ResourceLocation soyuz_luna_booster = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/booster.png"); public static final ResourceLocation soyuz_luna_boosterside = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_luna/boosterside.png"); public static final ResourceLocation soyuz_authentic_engineblock = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/engineblock.png"); public static final ResourceLocation soyuz_authentic_bottomstage = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/bottomstage.png"); public static final ResourceLocation soyuz_authentic_topstage = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/topstage.png"); public static final ResourceLocation soyuz_authentic_payload = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/payload.png"); public static final ResourceLocation soyuz_authentic_payloadblocks = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/payloadblocks.png"); public static final ResourceLocation soyuz_authentic_les = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/les.png"); public static final ResourceLocation soyuz_authentic_lesthrusters = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/lesthrusters.png"); public static final ResourceLocation soyuz_authentic_mainengines = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/mainengines.png"); public static final ResourceLocation soyuz_authentic_sideengines = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/sideengines.png"); public static final ResourceLocation soyuz_authentic_booster = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/booster.png"); public static final ResourceLocation soyuz_authentic_boosterside = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_authentic/boosterside.png"); public static final ResourceLocation soyuz_memento = new ResourceLocation(RefStrings.MODID, "textures/items/polaroid_memento.png"); public static final ResourceLocation soyuz_lander_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_capsule/soyuz_lander.png"); public static final ResourceLocation soyuz_lander_rust_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_capsule/soyuz_lander_rust.png"); public static final ResourceLocation soyuz_chute_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_capsule/soyuz_chute.png"); public static final ResourceLocation soyuz_module_dome_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_capsule/module_dome.png"); public static final ResourceLocation soyuz_module_lander_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_capsule/module_lander.png"); public static final ResourceLocation soyuz_module_propulsion_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_capsule/module_propulsion.png"); public static final ResourceLocation soyuz_module_solar_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_capsule/module_solar.png"); public static final ResourceLocation soyuz_launcher_legs_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_launcher/launcher_leg.png"); public static final ResourceLocation soyuz_launcher_table_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_launcher/launcher_table.png"); public static final ResourceLocation soyuz_launcher_tower_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_launcher/launcher_tower_base.png"); public static final ResourceLocation soyuz_launcher_tower_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_launcher/launcher_tower.png"); public static final ResourceLocation soyuz_launcher_support_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_launcher/launcher_support_base.png"); public static final ResourceLocation soyuz_launcher_support_tex = new ResourceLocation(RefStrings.MODID, "textures/models/soyuz_launcher/launcher_support.png"); //Missile Parts public static final ResourceLocation missile_pad_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missilePad.png"); public static final ResourceLocation missile_assembly_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_assembly.png"); public static final ResourceLocation strut_tex = new ResourceLocation(RefStrings.MODID, "textures/models/strut.png"); public static final ResourceLocation compact_launcher_tex = new ResourceLocation(RefStrings.MODID, "textures/models/compact_launcher.png"); public static final ResourceLocation launch_table_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/launch_table.png"); public static final ResourceLocation launch_table_large_pad_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/launch_table_large_pad.png"); public static final ResourceLocation launch_table_small_pad_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/launch_table_small_pad.png"); public static final ResourceLocation launch_table_large_scaffold_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/launch_table_large_scaffold_base.png"); public static final ResourceLocation launch_table_large_scaffold_connector_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/launch_table_large_scaffold_connector.png"); public static final ResourceLocation launch_table_small_scaffold_base_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/launch_table_small_scaffold_base.png"); public static final ResourceLocation launch_table_small_scaffold_connector_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/launch_table_small_scaffold_connector.png"); public static final ResourceLocation mp_t_10_kerosene_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_10_kerosene.png"); public static final ResourceLocation mp_t_10_solid_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_10_solid.png"); public static final ResourceLocation mp_t_10_xenon_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_10_xenon.png"); public static final ResourceLocation mp_t_15_kerosene_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_15_kerosene.png"); public static final ResourceLocation mp_t_15_kerosene_dual_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_15_kerosene_dual.png"); public static final ResourceLocation mp_t_15_solid_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_15_solid.png"); public static final ResourceLocation mp_t_15_solid_hexdecuple_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_15_solid_hexdecuple.png"); public static final ResourceLocation mp_t_15_hydrogen_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_15_hydrogen.png"); public static final ResourceLocation mp_t_15_hydrogen_dual_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_15_hydrogen_dual.png"); public static final ResourceLocation mp_t_15_balefire_short_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_15_balefire_short.png"); public static final ResourceLocation mp_t_15_balefire_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_15_balefire.png"); public static final ResourceLocation mp_t_15_balefire_large_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_15_balefire_large.png"); public static final ResourceLocation mp_t_15_balefire_large_rad_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_15_balefire_large_rad.png"); public static final ResourceLocation mp_t_20_kerosene_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_20_kerosene.png"); public static final ResourceLocation mp_t_20_kerosene_dual_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_20_kerosene_dual.png"); public static final ResourceLocation mp_t_20_solid_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_20_solid.png"); public static final ResourceLocation mp_t_20_solid_multi_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_20_solid_multi.png"); public static final ResourceLocation mp_t_20_solid_multier_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/thrusters/mp_t_20_solid_multier.png"); public static final ResourceLocation mp_s_10_flat_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/stability/mp_s_10_flat.png"); public static final ResourceLocation mp_s_10_cruise_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/stability/mp_s_10_cruise.png"); public static final ResourceLocation mp_s_10_space_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/stability/mp_s_10_space.png"); public static final ResourceLocation mp_s_15_flat_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/stability/mp_s_15_flat.png"); public static final ResourceLocation mp_s_15_thin_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/stability/mp_s_15_thin.png"); public static final ResourceLocation mp_s_15_soyuz_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/stability/mp_s_15_soyuz.png"); public static final ResourceLocation mp_f_10_kerosene_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_kerosene.png"); public static final ResourceLocation mp_f_10_kerosene_camo_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_kerosene_camo.png"); public static final ResourceLocation mp_f_10_kerosene_desert_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_kerosene_desert.png"); public static final ResourceLocation mp_f_10_kerosene_sky_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_kerosene_sky.png"); public static final ResourceLocation mp_f_10_kerosene_flames_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_kerosene_flames.png"); public static final ResourceLocation mp_f_10_kerosene_insulation_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_kerosene_insulation.png"); public static final ResourceLocation mp_f_10_kerosene_sleek_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_kerosene_sleek.png"); public static final ResourceLocation mp_f_10_kerosene_metal_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_kerosene_metal.png"); public static final ResourceLocation mp_f_10_kerosene_taint_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_10_kerosene_taint.png"); public static final ResourceLocation mp_f_10_solid_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_solid.png"); public static final ResourceLocation mp_f_10_solid_flames_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_solid_flames.png"); public static final ResourceLocation mp_f_10_solid_insulation_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_solid_insulation.png"); public static final ResourceLocation mp_f_10_solid_sleek_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_solid_sleek.png"); public static final ResourceLocation mp_f_10_solid_soviet_glory_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_solid_soviet_glory.png"); public static final ResourceLocation mp_f_10_solid_moonlit_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_10_solid_moonlit.png"); public static final ResourceLocation mp_f_10_solid_cathedral_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_10_solid_cathedral.png"); public static final ResourceLocation mp_f_10_solid_battery_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_10_solid_battery.png"); public static final ResourceLocation mp_f_10_solid_duracell_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_solid_duracell.png"); public static final ResourceLocation mp_f_10_xenon_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_xenon.png"); public static final ResourceLocation mp_f_10_xenon_bhole_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_10_xenon_bhole.png"); public static final ResourceLocation mp_f_10_long_kerosene_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_kerosene.png"); public static final ResourceLocation mp_f_10_long_kerosene_camo_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_kerosene_camo.png"); public static final ResourceLocation mp_f_10_long_kerosene_desert_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_kerosene_desert.png"); public static final ResourceLocation mp_f_10_long_kerosene_sky_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_kerosene_sky.png"); public static final ResourceLocation mp_f_10_long_kerosene_flames_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_kerosene_flames.png"); public static final ResourceLocation mp_f_10_long_kerosene_insulation_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_kerosene_insulation.png"); public static final ResourceLocation mp_f_10_long_kerosene_sleek_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_kerosene_sleek.png"); public static final ResourceLocation mp_f_10_long_kerosene_metal_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_kerosene_metal.png"); public static final ResourceLocation mp_f_10_long_kerosene_dash_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_10_long_kerosene_dash.png"); public static final ResourceLocation mp_f_10_long_kerosene_taint_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_10_long_kerosene_taint.png"); public static final ResourceLocation mp_f_10_long_kerosene_vap_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_10_long_kerosene_vap.png"); public static final ResourceLocation mp_f_10_long_solid_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_solid.png"); public static final ResourceLocation mp_f_10_long_solid_flames_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_solid_flames.png"); public static final ResourceLocation mp_f_10_long_solid_insulation_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_solid_insulation.png"); public static final ResourceLocation mp_f_10_long_solid_sleek_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_solid_sleek.png"); public static final ResourceLocation mp_f_10_long_solid_soviet_glory_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_long_solid_soviet_glory.png"); public static final ResourceLocation mp_f_10_long_solid_bullet_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_10_long_solid_bullet.png"); public static final ResourceLocation mp_f_10_long_solid_silvermoonlight_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_10_long_solid_silvermoonlight.png"); public static final ResourceLocation mp_f_10_15_kerosene_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_15_kerosene.png"); public static final ResourceLocation mp_f_10_15_solid_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_15_solid.png"); public static final ResourceLocation mp_f_10_15_hydrogen_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_15_hydrogen.png"); public static final ResourceLocation mp_f_10_15_balefire_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_10_15_balefire.png"); public static final ResourceLocation mp_f_15_kerosene_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_kerosene.png"); public static final ResourceLocation mp_f_15_kerosene_camo_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_kerosene_camo.png"); public static final ResourceLocation mp_f_15_kerosene_desert_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_kerosene_desert.png"); public static final ResourceLocation mp_f_15_kerosene_sky_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_kerosene_sky.png"); public static final ResourceLocation mp_f_15_kerosene_insulation_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_kerosene_insulation.png"); public static final ResourceLocation mp_f_15_kerosene_metal_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_kerosene_metal.png"); public static final ResourceLocation mp_f_15_kerosene_decorated_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_kerosene_decorated.png"); public static final ResourceLocation mp_f_15_kerosene_steampunk_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_kerosene_steampunk.png"); public static final ResourceLocation mp_f_15_kerosene_polite_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_kerosene_polite.png"); public static final ResourceLocation mp_f_15_kerosene_blackjack_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/base/mp_f_15_kerosene_blackjack.png"); public static final ResourceLocation mp_f_15_kerosene_lambda_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_15_kerosene_lambda.png"); public static final ResourceLocation mp_f_15_kerosene_minuteman_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_15_kerosene_minuteman.png"); public static final ResourceLocation mp_f_15_kerosene_pip_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_15_kerosene_pip.png"); public static final ResourceLocation mp_f_15_kerosene_taint_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_15_kerosene_taint.png"); public static final ResourceLocation mp_f_15_kerosene_yuck_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_kerosene_yuck.png"); public static final ResourceLocation mp_f_15_solid_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_solid.png"); public static final ResourceLocation mp_f_15_solid_insulation_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_solid_insulation.png"); public static final ResourceLocation mp_f_15_solid_desh_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_solid_desh.png"); public static final ResourceLocation mp_f_15_solid_soviet_glory_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_solid_soviet_glory.png"); public static final ResourceLocation mp_f_15_solid_soviet_stank_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_solid_soviet_stank.png"); public static final ResourceLocation mp_f_15_solid_faust_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_15_solid_faust.png"); public static final ResourceLocation mp_f_15_solid_silvermoonlight_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_15_solid_silvermoonlight.png"); public static final ResourceLocation mp_f_15_solid_snowy_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_15_solid_snowy.png"); public static final ResourceLocation mp_f_15_solid_panorama_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_solid_panorama.png"); public static final ResourceLocation mp_f_15_solid_roses_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_solid_roses.png"); public static final ResourceLocation mp_f_15_hydrogen_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_hydrogen.png"); public static final ResourceLocation mp_f_15_hydrogen_cathedral_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/contest/mp_f_15_hydrogen_cathedral.png"); public static final ResourceLocation mp_f_15_balefire_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_balefire.png"); public static final ResourceLocation mp_f_15_20_kerosene_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_20_kerosene.png"); public static final ResourceLocation mp_f_15_20_kerosene_magnusson_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_20_kerosene_magnusson.png"); public static final ResourceLocation mp_f_15_20_solid_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/fuselages/mp_f_15_20_solid.png"); public static final ResourceLocation mp_w_10_he_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_10_he.png"); public static final ResourceLocation mp_w_10_incendiary_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_10_incendiary.png"); public static final ResourceLocation mp_w_10_buster_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_10_buster.png"); public static final ResourceLocation mp_w_10_nuclear_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_10_nuclear.png"); public static final ResourceLocation mp_w_10_nuclear_large_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_10_nuclear_large.png"); public static final ResourceLocation mp_w_10_taint_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_10_taint.png"); public static final ResourceLocation mp_w_10_cloud_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_10_cloud.png"); public static final ResourceLocation mp_w_15_he_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_he.png"); public static final ResourceLocation mp_w_15_incendiary_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_incendiary.png"); public static final ResourceLocation mp_w_15_nuclear_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_nuclear.png"); public static final ResourceLocation mp_w_15_nuclear_shark_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_nuclear_shark.png"); public static final ResourceLocation mp_w_15_thermo_moon_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_nuclear_moon.png"); public static final ResourceLocation mp_w_15_n2_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_n2.png"); public static final ResourceLocation mp_w_15_balefire_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_balefire.png"); public static final ResourceLocation mp_w_15_turbine_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_turbine.png"); public static final ResourceLocation mp_w_15_schrab_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_schrab.png"); public static final ResourceLocation mp_w_15_schrab_australium_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_nuclear_australium.png"); public static final ResourceLocation mp_w_15_mirv_tex = new ResourceLocation(RefStrings.MODID, "textures/models/missile_parts/warheads/mp_w_15_mirv.png"); //Carts public static final ResourceLocation cart_metal = new ResourceLocation(RefStrings.MODID, "textures/entity/cart_metal.png"); public static final ResourceLocation cart_blank = new ResourceLocation(RefStrings.MODID, "textures/entity/cart_metal_naked.png"); public static final ResourceLocation cart_wood = new ResourceLocation(RefStrings.MODID, "textures/entity/cart_wood.png"); public static final ResourceLocation cart_destroyer_tex = new ResourceLocation(RefStrings.MODID, "textures/entity/cart_destroyer.png"); public static final ResourceLocation cart_powder_tex = new ResourceLocation(RefStrings.MODID, "textures/blocks/block_gunpowder.png"); public static final ResourceLocation cart_semtex_side = new ResourceLocation(RefStrings.MODID, "textures/blocks/semtex_side.png"); public static final ResourceLocation cart_semtex_top = new ResourceLocation(RefStrings.MODID, "textures/blocks/semtex_bottom.png"); //ISBRHs public static final IModelCustom scaffold = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/scaffold.obj")); public static final IModelCustom taperecorder = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/taperecorder.obj")); public static final IModelCustom beam = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/beam.obj")); public static final IModelCustom barrel = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/barrel.obj")); public static final IModelCustom pole = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/pole.obj")); public static final IModelCustom barbed_wire = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/barbed_wire.obj")); public static final IModelCustom spikes = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/spikes.obj")); public static final IModelCustom antenna_top = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/antenna_top.obj")); public static final IModelCustom conservecrate = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/conservecrate.obj")); public static final IModelCustom pipe = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/pipe.obj")); public static final IModelCustom pipe_rim = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/pipe_rim.obj")); public static final IModelCustom pipe_quad = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/pipe_quad.obj")); public static final IModelCustom pipe_frame = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/pipe_frame.obj")); public static final IModelCustom deco_computer = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/puter.obj")); public static final IModelCustom rbmk_element = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/rbmk/rbmk_element.obj")); public static final IModelCustom rbmk_reflector = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/rbmk/rbmk_reflector.obj")); public static final IModelCustom rbmk_rods = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/rbmk/rbmk_rods.obj")); public static final IModelCustom rbmk_crane_console = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/rbmk/crane_console.obj")); public static final IModelCustom rbmk_crane = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/rbmk/crane.obj")); public static final IModelCustom rbmk_console = new HFRWavefrontObject(new ResourceLocation(RefStrings.MODID, "models/rbmk/rbmk_console.obj")); public static final IModelCustom rbmk_debris = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/rbmk/debris.obj")); public static final ResourceLocation rbmk_crane_console_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/crane_console.png"); public static final ResourceLocation rbmk_crane_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/rbmk_crane.png"); public static final ResourceLocation rbmk_console_tex = new ResourceLocation(RefStrings.MODID, "textures/models/machines/rbmk_control.png"); public static final IModelCustom hev_battery = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/battery.obj")); public static final IModelCustom anvil = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/anvil.obj")); public static final IModelCustom crystal_power = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/crystals_power.obj")); public static final IModelCustom crystal_energy = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/crystals_energy.obj")); public static final IModelCustom crystal_robust = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/crystals_robust.obj")); public static final IModelCustom crystal_trixite = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/crystals_trixite.obj")); public static final IModelCustom cable_neo = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/cable_neo.obj")); public static final IModelCustom pipe_neo = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/pipe_neo.obj")); public static final IModelCustom charge_dynamite = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/charge_dynamite.obj")); public static final IModelCustom charge_c4 = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/blocks/charge_c4.obj")); //RBMK DEBRIS public static final IModelCustom deb_blank = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/projectiles/deb_blank.obj")); public static final IModelCustom deb_element = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/projectiles/deb_element.obj")); public static final IModelCustom deb_fuel = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/projectiles/deb_fuel.obj")); public static final IModelCustom deb_rod = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/projectiles/deb_rod.obj")); public static final IModelCustom deb_lid = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/projectiles/deb_lid.obj")); public static final IModelCustom deb_graphite = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/projectiles/deb_graphite.obj")); public static final IModelCustom deb_zirnox_blank = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/zirnox/deb_blank.obj")); public static final IModelCustom deb_zirnox_concrete = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/zirnox/deb_concrete.obj")); public static final IModelCustom deb_zirnox_element = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/zirnox/deb_element.obj")); public static final IModelCustom deb_zirnox_exchanger = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/zirnox/deb_exchanger.obj")); public static final IModelCustom deb_zirnox_shrapnel = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/zirnox/deb_shrapnel.obj")); public static void loadAnimatedModels(){ transition_seal = ColladaLoader.load(new ResourceLocation(RefStrings.MODID, "models/doors/seal.dae"), true); transition_seal_anim = ColladaLoader.loadAnim(24040, new ResourceLocation(RefStrings.MODID, "models/doors/seal.dae")); } }
70000hp/Hbm-s-Nuclear-Tech-GIT
src/main/java/com/hbm/main/ResourceManager.java
213,986
package shared.reader; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import shared.DataSet; import shared.DataSetDescription; import shared.Instance; import util.linalg.DenseVector; /** * Class to read in data from a ARFF file * @author Jarvis Johnson <https://github.com/Magicjarvis> * @author Alex Linton <https://github.com/lexlinton> * @date 2013-03-05 */ public class ArffDataSetReader extends DataSetReader { private final String DATA_TAG = "@data"; private final String ATTRIBUTE_TAG = "@attribute"; private final int SPLIT_LIMIT = 3; public ArffDataSetReader(String file) { super(file); } @Override public DataSet read() throws Exception { BufferedReader in = new BufferedReader(new FileReader(file)); try { List<Map<String, Double>> attributes = processAttributes(in); Instance[] instances = processInstances(in, attributes); DataSet set = new DataSet(instances); set.setDescription(new DataSetDescription(set)); return set; } finally { // don't forget to close the buffer in.close(); } } /** * Parses the buffer in to a map attribute-> * @param in Buffer to read from * @return Hashmap linking attributes to numeric values * @throws IOException */ private List<Map<String, Double>> processAttributes(BufferedReader in) throws IOException { String line = in.readLine(); List<Map<String, Double>> attributes = new ArrayList<Map<String, Double>>(); while (line != null && line.toLowerCase().indexOf(DATA_TAG) == -1) { if (!line.isEmpty() && line.charAt(0) != '%') { String[] parts = line.split("\\s", SPLIT_LIMIT); if (parts[0].equalsIgnoreCase(ATTRIBUTE_TAG)) { // process any attribute values //NOTE: for REAL and INTEGER types, this will do nothing but those types are handled // in processInstances String[] values = parts[2].replaceAll(" |\\{|\\}|'","").split(","); double id = 0.0; Map<String, Double> valMap = new HashMap<String, Double>(); for (String s : values) { s = s.trim(); //trim off whitespace valMap.put(s, id++); } attributes.add(valMap); } } line = in.readLine(); } return attributes; } private Instance[] processInstances(BufferedReader in, List<Map<String, Double>> valueMaps) throws IOException { List<Instance> instances = new ArrayList<Instance>(); String line = in.readLine(); Pattern pattern = Pattern.compile("[ ,]+"); while (line != null) { if (!line.isEmpty() && line.charAt(0) != '%') { String[] values = pattern.split(line.trim()); double[] ins = new double[values.length]; for (int i = 0; i < values.length; i++) { //some values are single quoted (especially in datafiles bundled // with weka) String v = values[i].replaceAll("'", ""); // defaulting to 0 if attribute value unknown. double d = 0; try { d = Double.parseDouble(v); } catch(NumberFormatException e){ if (valueMaps.get(i).containsKey(v)) { d = valueMaps.get(i).get(v); } } ins[i] = d; } Instance i = new Instance(new DenseVector(Arrays.copyOfRange(ins, 0, ins.length - 1)), new Instance(ins[ins.length - 1])); // This assumes the class label is the last attribute. User should change if that's not the case instances.add(i); } line = in.readLine(); } return instances.toArray(new Instance[instances.size()]); } }
pushkar/ABAGAIL
src/shared/reader/ArffDataSetReader.java
213,987
/* NOTICE: This file has been changed by Plutext Pty Ltd for use in docx4j. * The package name has been changed; there may also be other changes. * * This notice is included to meet the condition in clause 4(b) of the License. */ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.docx4j.org.apache.poi.poifs.property; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import org.docx4j.org.apache.poi.hpsf.ClassID; import org.docx4j.org.apache.poi.poifs.common.POIFSConstants; import org.docx4j.org.apache.poi.poifs.dev.POIFSViewable; import org.docx4j.org.apache.poi.util.ByteField; import org.docx4j.org.apache.poi.util.IntegerField; import org.docx4j.org.apache.poi.util.LittleEndianConsts; import org.docx4j.org.apache.poi.util.ShortField; /** * This abstract base class is the ancestor of all classes * implementing POIFS Property behavior. * * @author Marc Johnson (mjohnson at apache dot org) */ public abstract class Property implements Child, POIFSViewable { static final private byte _default_fill = ( byte ) 0x00; static final private int _name_size_offset = 0x40; static final private int _max_name_length = (_name_size_offset / LittleEndianConsts.SHORT_SIZE) - 1; static final protected int _NO_INDEX = -1; // useful offsets static final private int _node_color_offset = 0x43; static final private int _previous_property_offset = 0x44; static final private int _next_property_offset = 0x48; static final private int _child_property_offset = 0x4C; static final private int _storage_clsid_offset = 0x50; static final private int _user_flags_offset = 0x60; static final private int _seconds_1_offset = 0x64; static final private int _days_1_offset = 0x68; static final private int _seconds_2_offset = 0x6C; static final private int _days_2_offset = 0x70; static final private int _start_block_offset = 0x74; static final private int _size_offset = 0x78; // node colors static final protected byte _NODE_BLACK = 1; static final protected byte _NODE_RED = 0; // documents must be at least this size to be stored in big blocks static final private int _big_block_minimum_bytes = POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE; private String _name; private ShortField _name_size; private ByteField _property_type; private ByteField _node_color; private IntegerField _previous_property; private IntegerField _next_property; private IntegerField _child_property; private ClassID _storage_clsid; private IntegerField _user_flags; private IntegerField _seconds_1; private IntegerField _days_1; private IntegerField _seconds_2; private IntegerField _days_2; private IntegerField _start_block; private IntegerField _size; private byte[] _raw_data; private int _index; private Child _next_child; private Child _previous_child; protected Property() { _raw_data = new byte[ POIFSConstants.PROPERTY_SIZE ]; Arrays.fill(_raw_data, _default_fill); _name_size = new ShortField(_name_size_offset); _property_type = new ByteField(PropertyConstants.PROPERTY_TYPE_OFFSET); _node_color = new ByteField(_node_color_offset); _previous_property = new IntegerField(_previous_property_offset, _NO_INDEX, _raw_data); _next_property = new IntegerField(_next_property_offset, _NO_INDEX, _raw_data); _child_property = new IntegerField(_child_property_offset, _NO_INDEX, _raw_data); _storage_clsid = new ClassID(_raw_data,_storage_clsid_offset); _user_flags = new IntegerField(_user_flags_offset, 0, _raw_data); _seconds_1 = new IntegerField(_seconds_1_offset, 0, _raw_data); _days_1 = new IntegerField(_days_1_offset, 0, _raw_data); _seconds_2 = new IntegerField(_seconds_2_offset, 0, _raw_data); _days_2 = new IntegerField(_days_2_offset, 0, _raw_data); _start_block = new IntegerField(_start_block_offset); _size = new IntegerField(_size_offset, 0, _raw_data); _index = _NO_INDEX; setName(""); setNextChild(null); setPreviousChild(null); } /** * Constructor from byte data * * @param index index number * @param array byte data * @param offset offset into byte data */ protected Property(int index, byte [] array, int offset) { _raw_data = new byte[ POIFSConstants.PROPERTY_SIZE ]; System.arraycopy(array, offset, _raw_data, 0, POIFSConstants.PROPERTY_SIZE); _name_size = new ShortField(_name_size_offset, _raw_data); _property_type = new ByteField(PropertyConstants.PROPERTY_TYPE_OFFSET, _raw_data); _node_color = new ByteField(_node_color_offset, _raw_data); _previous_property = new IntegerField(_previous_property_offset, _raw_data); _next_property = new IntegerField(_next_property_offset, _raw_data); _child_property = new IntegerField(_child_property_offset, _raw_data); _storage_clsid = new ClassID(_raw_data,_storage_clsid_offset); _user_flags = new IntegerField(_user_flags_offset, 0, _raw_data); _seconds_1 = new IntegerField(_seconds_1_offset, _raw_data); _days_1 = new IntegerField(_days_1_offset, _raw_data); _seconds_2 = new IntegerField(_seconds_2_offset, _raw_data); _days_2 = new IntegerField(_days_2_offset, _raw_data); _start_block = new IntegerField(_start_block_offset, _raw_data); _size = new IntegerField(_size_offset, _raw_data); _index = index; int name_length = (_name_size.get() / LittleEndianConsts.SHORT_SIZE) - 1; if (name_length < 1) { _name = ""; } else { char[] char_array = new char[ name_length ]; int name_offset = 0; for (int j = 0; j < name_length; j++) { char_array[ j ] = ( char ) new ShortField(name_offset, _raw_data).get(); name_offset += LittleEndianConsts.SHORT_SIZE; } _name = new String(char_array, 0, name_length); } _next_child = null; _previous_child = null; } /** * Write the raw data to an OutputStream. * * @param stream the OutputStream to which the data should be * written. * * @exception IOException on problems writing to the specified * stream. */ public void writeData(OutputStream stream) throws IOException { stream.write(_raw_data); } /** * Set the start block for the document referred to by this * Property. * * @param startBlock the start block index */ public void setStartBlock(int startBlock) { _start_block.set(startBlock, _raw_data); } /** * @return the start block */ public int getStartBlock() { return _start_block.get(); } /** * find out the document size * * @return size in bytes */ public int getSize() { return _size.get(); } /** * Based on the currently defined size, should this property use * small blocks? * * @return true if the size is less than _big_block_minimum_bytes */ public boolean shouldUseSmallBlocks() { return Property.isSmall(_size.get()); } /** * does the length indicate a small document? * * @param length length in bytes * * @return true if the length is less than * _big_block_minimum_bytes */ public static boolean isSmall(int length) { return length < _big_block_minimum_bytes; } /** * Get the name of this property * * @return property name as String */ public String getName() { return _name; } /** * @return true if a directory type Property */ abstract public boolean isDirectory(); /** * Sets the storage clsid, which is the Class ID of a COM object which * reads and writes this stream * @return storage Class ID for this property stream */ public ClassID getStorageClsid() { return _storage_clsid; } /** * Set the name; silently truncates the name if it's too long. * * @param name the new name */ protected void setName(String name) { char[] char_array = name.toCharArray(); int limit = Math.min(char_array.length, _max_name_length); _name = new String(char_array, 0, limit); short offset = 0; int j = 0; for (; j < limit; j++) { new ShortField(offset, ( short ) char_array[ j ], _raw_data); offset += LittleEndianConsts.SHORT_SIZE; } for (; j < _max_name_length + 1; j++) { new ShortField(offset, ( short ) 0, _raw_data); offset += LittleEndianConsts.SHORT_SIZE; } // double the count, and include the null at the end _name_size .set(( short ) ((limit + 1) * LittleEndianConsts.SHORT_SIZE), _raw_data); } /** * Sets the storage class ID for this property stream. This is the Class ID * of the COM object which can read and write this property stream * @param clsidStorage Storage Class ID */ public void setStorageClsid( ClassID clsidStorage) { _storage_clsid = clsidStorage; if( clsidStorage == null) { Arrays.fill( _raw_data, _storage_clsid_offset, _storage_clsid_offset + ClassID.LENGTH, (byte) 0); } else { clsidStorage.write( _raw_data, _storage_clsid_offset); } } /** * Set the property type. Makes no attempt to validate the value. * * @param propertyType the property type (root, file, directory) */ protected void setPropertyType(byte propertyType) { _property_type.set(propertyType, _raw_data); } /** * Set the node color. * * @param nodeColor the node color (red or black) */ protected void setNodeColor(byte nodeColor) { _node_color.set(nodeColor, _raw_data); } /** * Set the child property. * * @param child the child property's index in the Property Table */ protected void setChildProperty(int child) { _child_property.set(child, _raw_data); } /** * Get the child property (its index in the Property Table) * * @return child property index */ protected int getChildIndex() { return _child_property.get(); } /** * Set the size of the document associated with this Property * * @param size the size of the document, in bytes */ protected void setSize(int size) { _size.set(size, _raw_data); } /** * Set the index for this Property * * @param index this Property's index within its containing * Property Table */ protected void setIndex(int index) { _index = index; } /** * get the index for this Property * * @return the index of this Property within its Property Table */ protected int getIndex() { return _index; } /** * Perform whatever activities need to be performed prior to * writing */ abstract protected void preWrite(); /** * get the next sibling * * @return index of next sibling */ int getNextChildIndex() { return _next_property.get(); } /** * get the previous sibling * * @return index of previous sibling */ int getPreviousChildIndex() { return _previous_property.get(); } /** * determine whether the specified index is valid * * @param index value to be checked * * @return true if the index is valid */ static boolean isValidIndex(int index) { return index != _NO_INDEX; } /** * Get the next Child, if any * * @return the next Child; may return null */ public Child getNextChild() { return _next_child; } /** * Get the previous Child, if any * * @return the previous Child; may return null */ public Child getPreviousChild() { return _previous_child; } /** * Set the next Child * * @param child the new 'next' child; may be null, which has the * effect of saying there is no 'next' child */ public void setNextChild(Child child) { _next_child = child; _next_property.set((child == null) ? _NO_INDEX : (( Property ) child) .getIndex(), _raw_data); } /** * Set the previous Child * * @param child the new 'previous' child; may be null, which has * the effect of saying there is no 'previous' child */ public void setPreviousChild(Child child) { _previous_child = child; _previous_property.set((child == null) ? _NO_INDEX : (( Property ) child) .getIndex(), _raw_data); } /** * Get an array of objects, some of which may implement * POIFSViewable * * @return an array of Object; may not be null, but may be empty */ public Object [] getViewableArray() { Object[] results = new Object[ 5 ]; results[ 0 ] = "Name = \"" + getName() + "\""; results[ 1 ] = "Property Type = " + _property_type.get(); results[ 2 ] = "Node Color = " + _node_color.get(); long time = _days_1.get(); time <<= 32; time += _seconds_1.get() & 0x0000FFFFL; results[ 3 ] = "Time 1 = " + time; time = _days_2.get(); time <<= 32; time += _seconds_2.get() & 0x0000FFFFL; results[ 4 ] = "Time 2 = " + time; return results; } /** * Get an Iterator of objects, some of which may implement * POIFSViewable * * @return an Iterator; may not be null, but may have an empty * back end store */ public Iterator<Object> getViewableIterator() { return Collections.emptyList().iterator(); } /** * Give viewers a hint as to whether to call getViewableArray or * getViewableIterator * * @return true if a viewer should call getViewableArray, false if * a viewer should call getViewableIterator */ public boolean preferArray() { return true; } /** * Provides a short description of the object, to be used when a * POIFSViewable object has not provided its contents. * * @return short description */ public String getShortDescription() { StringBuffer buffer = new StringBuffer(); buffer.append("Property: \"").append(getName()).append("\""); return buffer.toString(); } }
plutext/docx4j
docx4j-core/src/main/java/org/docx4j/org/apache/poi/poifs/property/Property.java
213,988
/* * Copyright 1999,2004 The Apache Software Foundation. * * 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. * * Created for feature LIDB4147-9 "Integrate Unified Expression Language" 2006/08/14 Scott Johnson * Modified for jsp2.1ELwork */ package org.apache.jasper.compiler; import java.util.*; import javax.servlet.jsp.tagext.FunctionInfo; import com.ibm.ws.jsp.translator.JspTranslationException; /** * This class defines internal representation for an EL Expression * * It currently only defines functions. It can be expanded to define * all the components of an EL expression, if need to. * * @author Kin-man Chung */ public abstract class ELNode { abstract public void accept(Visitor v) throws JspTranslationException; /** * Child classes */ /** * Represents an EL expression: anything in ${ and }. */ public static class Root extends ELNode { private ELNode.Nodes expr; private char type; Root(ELNode.Nodes expr, char type) { this.expr = expr; this.type = type; } public void accept(Visitor v) throws JspTranslationException { v.visit(this); } public ELNode.Nodes getExpression() { return expr; } public char getType() { return type; } } /** * Represents text outside of EL expression. */ public static class Text extends ELNode { private String text; Text(String text) { this.text = text; } public void accept(Visitor v) throws JspTranslationException { v.visit(this); } public String getText() { return text; } } /** * Represents anything in EL expression, other than functions, including * function arguments etc */ public static class ELText extends ELNode { private String text; ELText(String text) { this.text = text; } public void accept(Visitor v) throws JspTranslationException { v.visit(this); } public String getText() { return text; } } /** * Represents a function * Currently only include the prefix and function name, but not its * arguments. */ public static class Function extends ELNode { private String prefix; private String name; private String uri; private FunctionInfo functionInfo; private String methodName; private String[] parameters; Function(String prefix, String name) { this.prefix = prefix; this.name = name; } public void accept(Visitor v) throws JspTranslationException { v.visit(this); } public String getPrefix() { return prefix; } public String getName() { return name; } public void setUri(String uri) { this.uri = uri; } public String getUri() { return uri; } public void setFunctionInfo(FunctionInfo f) { this.functionInfo = f; } public FunctionInfo getFunctionInfo() { return functionInfo; } public void setMethodName(String methodName) { this.methodName = methodName; } public String getMethodName() { return methodName; } public void setParameters(String[] parameters) { this.parameters = parameters; } public String[] getParameters() { return parameters; } } /** * An ordered list of ELNode. */ public static class Nodes { /* Name used for creating a map for the functions in this EL expression, for communication to Generator. */ String mapName = null; // The function map associated this EL private List<ELNode> list; public Nodes() { list = new ArrayList<ELNode>(); } public void add(ELNode en) { list.add(en); } /** * Visit the nodes in the list with the supplied visitor * @param v The visitor used */ public void visit(Visitor v) throws JspTranslationException { Iterator<ELNode> iter = list.iterator(); while (iter.hasNext()) { ELNode n = iter.next(); n.accept(v); } } public Iterator<ELNode> iterator() { return list.iterator(); } public boolean isEmpty() { return list.size() == 0; } /** * @return true if the expression contains a ${...} */ public boolean containsEL() { Iterator<ELNode> iter = list.iterator(); while (iter.hasNext()) { ELNode n = iter.next(); if (n instanceof Root) { return true; } } return false; } public void setMapName(String name) { this.mapName = name; } public String getMapName() { return mapName; } } /* * A visitor class for traversing ELNodes */ public static class Visitor { public void visit(Root n) throws JspTranslationException { n.getExpression().visit(this); } public void visit(Function n) throws JspTranslationException { } public void visit(Text n) throws JspTranslationException { } public void visit(ELText n) throws JspTranslationException { } } }
tjwatson/open-liberty
dev/com.ibm.ws.jsp/src/org/apache/jasper/compiler/ELNode.java
213,989
/* * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.springframework.transaction.interceptor; import java.util.Collection; import java.util.Collections; import java.util.Set; import org.springframework.lang.Nullable; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.util.StringValueResolver; /** * Spring's common transaction attribute implementation. * Rolls back on runtime, but not checked, exceptions by default. * * @author Rod Johnson * @author Juergen Hoeller * @author Mark Paluch * @since 16.03.2003 */ @SuppressWarnings("serial") public class DefaultTransactionAttribute extends DefaultTransactionDefinition implements TransactionAttribute { @Nullable private String descriptor; @Nullable private String timeoutString; @Nullable private String qualifier; private Collection<String> labels = Collections.emptyList(); /** * Create a new {@code DefaultTransactionAttribute} with default settings. * Can be modified through bean property setters. * @see #setPropagationBehavior * @see #setIsolationLevel * @see #setTimeout * @see #setReadOnly * @see #setName */ public DefaultTransactionAttribute() { } /** * Copy constructor. Definition can be modified through bean property setters. * @see #setPropagationBehavior * @see #setIsolationLevel * @see #setTimeout * @see #setReadOnly * @see #setName */ public DefaultTransactionAttribute(TransactionAttribute other) { super(other); } /** * Create a new {@code DefaultTransactionAttribute} with the given * propagation behavior. Can be modified through bean property setters. * @param propagationBehavior one of the propagation constants in the * TransactionDefinition interface * @see #setIsolationLevel * @see #setTimeout * @see #setReadOnly */ public DefaultTransactionAttribute(int propagationBehavior) { super(propagationBehavior); } /** * Set a descriptor for this transaction attribute, * e.g. indicating where the attribute is applying. * @since 4.3.4 */ public void setDescriptor(@Nullable String descriptor) { this.descriptor = descriptor; } /** * Return a descriptor for this transaction attribute, * or {@code null} if none. * @since 4.3.4 */ @Nullable public String getDescriptor() { return this.descriptor; } /** * Set the timeout to apply, if any, * as a String value that resolves to a number of seconds. * @since 5.3 * @see #setTimeout * @see #resolveAttributeStrings */ public void setTimeoutString(@Nullable String timeoutString) { this.timeoutString = timeoutString; } /** * Return the timeout to apply, if any, * as a String value that resolves to a number of seconds. * @since 5.3 * @see #getTimeout * @see #resolveAttributeStrings */ @Nullable public String getTimeoutString() { return this.timeoutString; } /** * Associate a qualifier value with this transaction attribute. * <p>This may be used for choosing a corresponding transaction manager * to process this specific transaction. * @since 3.0 * @see #resolveAttributeStrings */ public void setQualifier(@Nullable String qualifier) { this.qualifier = qualifier; } /** * Return a qualifier value associated with this transaction attribute. * @since 3.0 */ @Override @Nullable public String getQualifier() { return this.qualifier; } /** * Associate one or more labels with this transaction attribute. * <p>This may be used for applying specific transactional behavior * or follow a purely descriptive nature. * @since 5.3 * @see #resolveAttributeStrings */ public void setLabels(Collection<String> labels) { this.labels = labels; } @Override public Collection<String> getLabels() { return this.labels; } /** * The default behavior is as with EJB: rollback on unchecked exception * ({@link RuntimeException}), assuming an unexpected outcome outside any * business rules. Additionally, we also attempt to rollback on {@link Error} which * is clearly an unexpected outcome as well. By contrast, a checked exception is * considered a business exception and therefore a regular expected outcome of the * transactional business method, i.e. a kind of alternative return value which * still allows for regular completion of resource operations. * <p>This is largely consistent with TransactionTemplate's default behavior, * except that TransactionTemplate also rolls back on undeclared checked exceptions * (a corner case). For declarative transactions, we expect checked exceptions to be * intentionally declared as business exceptions, leading to a commit by default. * @see org.springframework.transaction.support.TransactionTemplate#execute */ @Override public boolean rollbackOn(Throwable ex) { return (ex instanceof RuntimeException || ex instanceof Error); } /** * Resolve attribute values that are defined as resolvable Strings: * {@link #setTimeoutString}, {@link #setQualifier}, {@link #setLabels}. * This is typically used for resolving "${...}" placeholders. * @param resolver the embedded value resolver to apply, if any * @since 5.3 */ public void resolveAttributeStrings(@Nullable StringValueResolver resolver) { String timeoutString = this.timeoutString; if (StringUtils.hasText(timeoutString)) { if (resolver != null) { timeoutString = resolver.resolveStringValue(timeoutString); } if (StringUtils.hasLength(timeoutString)) { try { setTimeout(Integer.parseInt(timeoutString)); } catch (RuntimeException ex) { throw new IllegalArgumentException( "Invalid timeoutString value \"" + timeoutString + "\"; " + ex); } } } if (resolver != null) { if (this.qualifier != null) { this.qualifier = resolver.resolveStringValue(this.qualifier); } Set<String> resolvedLabels = CollectionUtils.newLinkedHashSet(this.labels.size()); for (String label : this.labels) { resolvedLabels.add(resolver.resolveStringValue(label)); } this.labels = resolvedLabels; } } /** * Return an identifying description for this transaction attribute. * <p>Available to subclasses, for inclusion in their {@code toString()} result. */ protected final StringBuilder getAttributeDescription() { StringBuilder result = getDefinitionDescription(); if (StringUtils.hasText(this.qualifier)) { result.append("; '").append(this.qualifier).append('\''); } if (!this.labels.isEmpty()) { result.append("; ").append(this.labels); } return result; } }
AgileByteIO/spring-framework
spring-tx/src/main/java/org/springframework/transaction/interceptor/DefaultTransactionAttribute.java
213,990
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package qunar.tc.bistoury.instrument.client.spring.el; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * Interface to discover parameter names for methods and constructors. * * <p>Parameter name discovery is not always possible, but various strategies are * available to try, such as looking for debug information that may have been * emitted at compile time, and looking for argname annotation values optionally * accompanying AspectJ annotated methods. * * @author Rod Johnson * @author Adrian Colyer * @since 2.0 */ interface ParameterNameDiscoverer { /** * Return parameter names for this method, * or {@code null} if they cannot be determined. * @param method method to find parameter names for * @return an array of parameter names if the names can be resolved, * or {@code null} if they cannot */ String[] getParameterNames(Method method); /** * Return parameter names for this constructor, * or {@code null} if they cannot be determined. * @param ctor constructor to find parameter names for * @return an array of parameter names if the names can be resolved, * or {@code null} if they cannot */ String[] getParameterNames(Constructor<?> ctor); }
qunarcorp/bistoury
bistoury-instrument-client/src/main/java/qunar/tc/bistoury/instrument/client/spring/el/ParameterNameDiscoverer.java
213,992
package mage.cards.p; import mage.MageInt; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.ExileSourceCost; import mage.abilities.effects.common.continuous.GainAbilityAllEffect; import mage.abilities.keyword.IndestructibleAbility; import mage.abilities.keyword.LifelinkAbility; import mage.abilities.keyword.VigilanceAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import mage.constants.SuperType; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.Predicates; import java.util.UUID; /** * * @author justinjohnson14 */ public final class PaladinDanseSteelMaverick extends CardImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent(); static { filter.add(Predicates.or( CardType.ARTIFACT.getPredicate(), SubType.HUMAN.getPredicate() )); } public PaladinDanseSteelMaverick(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{2}{W}"); this.supertype.add(SuperType.LEGENDARY); this.subtype.add(SubType.SYNTH); this.subtype.add(SubType.KNIGHT); this.power = new MageInt(3); this.toughness = new MageInt(3); // Vigilance this.addAbility(VigilanceAbility.getInstance()); // Lifelink this.addAbility(LifelinkAbility.getInstance()); // Exile Paladin Danse, Steel Maverick: Each creature you control that's an artifact or Human gains indestructible until end of turn. this.addAbility(new SimpleActivatedAbility( new GainAbilityAllEffect(IndestructibleAbility.getInstance(), Duration.EndOfTurn, filter) .setText("Each creature you control that's an artifact or Human gains indestructible until end of turn"), new ExileSourceCost() )); } private PaladinDanseSteelMaverick(final PaladinDanseSteelMaverick card) { super(card); } @Override public PaladinDanseSteelMaverick copy() { return new PaladinDanseSteelMaverick(this); } }
magefree/mage
Mage.Sets/src/mage/cards/p/PaladinDanseSteelMaverick.java
213,993
/* * * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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. */ import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleRelation; import javax.accessibility.AccessibleRelationSet; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultCellEditor; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.print.PrinterException; import java.util.Vector; import java.text.MessageFormat; /** * Table demo * * @author Philip Milne * @author Steve Wilson */ public class TableDemo extends DemoModule { JTable tableView; JScrollPane scrollpane; Dimension origin = new Dimension(0, 0); JCheckBox isColumnReorderingAllowedCheckBox; JCheckBox showHorizontalLinesCheckBox; JCheckBox showVerticalLinesCheckBox; JCheckBox isColumnSelectionAllowedCheckBox; JCheckBox isRowSelectionAllowedCheckBox; JLabel interCellSpacingLabel; JLabel rowHeightLabel; JSlider interCellSpacingSlider; JSlider rowHeightSlider; JComboBox<String> selectionModeComboBox = null; JComboBox<String> resizeModeComboBox = null; JLabel headerLabel; JLabel footerLabel; JTextField headerTextField; JTextField footerTextField; JCheckBox fitWidth; JButton printButton; JPanel controlPanel; JScrollPane tableAggregate; String path = "food/"; final int INITIAL_ROWHEIGHT = 33; /** * main method allows us to run as a standalone demo. */ public static void main(String[] args) { TableDemo demo = new TableDemo(null); demo.mainImpl(); } /** * TableDemo Constructor */ public TableDemo(SwingSet2 swingset) { super(swingset, "TableDemo", "toolbar/JTable.gif"); getDemoPanel().setLayout(new BorderLayout()); controlPanel = new JPanel(); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS)); JPanel cbPanel = new JPanel(new GridLayout(3, 2)); JPanel labelPanel = new JPanel(new GridLayout(2, 1)) { public Dimension getMaximumSize() { return new Dimension(getPreferredSize().width, super.getMaximumSize().height); } }; JPanel sliderPanel = new JPanel(new GridLayout(2, 1)) { public Dimension getMaximumSize() { return new Dimension(getPreferredSize().width, super.getMaximumSize().height); } }; JPanel comboPanel = new JPanel(new GridLayout(2, 1)); JPanel printPanel = new JPanel(new ColumnLayout()); getDemoPanel().add(controlPanel, BorderLayout.NORTH); Vector<JComponent> relatedComponents = new Vector<>(); // check box panel isColumnReorderingAllowedCheckBox = new JCheckBox(getString("TableDemo.reordering_allowed"), true); isColumnReorderingAllowedCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean flag = ((JCheckBox)e.getSource()).isSelected(); tableView.getTableHeader().setReorderingAllowed(flag); tableView.repaint(); } }); showHorizontalLinesCheckBox = new JCheckBox(getString("TableDemo.horz_lines"), true); showHorizontalLinesCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean flag = ((JCheckBox)e.getSource()).isSelected(); tableView.setShowHorizontalLines(flag); ; tableView.repaint(); } }); showVerticalLinesCheckBox = new JCheckBox(getString("TableDemo.vert_lines"), true); showVerticalLinesCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean flag = ((JCheckBox)e.getSource()).isSelected(); tableView.setShowVerticalLines(flag); ; tableView.repaint(); } }); // Show that showHorizontal/Vertical controls are related relatedComponents.removeAllElements(); relatedComponents.add(showHorizontalLinesCheckBox); relatedComponents.add(showVerticalLinesCheckBox); buildAccessibleGroup(relatedComponents); isRowSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.row_selection"), true); isRowSelectionAllowedCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean flag = ((JCheckBox)e.getSource()).isSelected(); tableView.setRowSelectionAllowed(flag); ; tableView.repaint(); } }); isColumnSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.column_selection"), false); isColumnSelectionAllowedCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean flag = ((JCheckBox)e.getSource()).isSelected(); tableView.setColumnSelectionAllowed(flag); ; tableView.repaint(); } }); // Show that row/column selections are related relatedComponents.removeAllElements(); relatedComponents.add(isColumnSelectionAllowedCheckBox); relatedComponents.add(isRowSelectionAllowedCheckBox); buildAccessibleGroup(relatedComponents); cbPanel.add(isColumnReorderingAllowedCheckBox); cbPanel.add(isRowSelectionAllowedCheckBox); cbPanel.add(showHorizontalLinesCheckBox); cbPanel.add(isColumnSelectionAllowedCheckBox); cbPanel.add(showVerticalLinesCheckBox); // label panel interCellSpacingLabel = new JLabel(getString("TableDemo.intercell_spacing_colon")); labelPanel.add(interCellSpacingLabel); rowHeightLabel = new JLabel(getString("TableDemo.row_height_colon")); labelPanel.add(rowHeightLabel); // slider panel interCellSpacingSlider = new JSlider(JSlider.HORIZONTAL, 0, 10, 1); interCellSpacingSlider.getAccessibleContext().setAccessibleName(getString("TableDemo.intercell_spacing")); interCellSpacingLabel.setLabelFor(interCellSpacingSlider); sliderPanel.add(interCellSpacingSlider); interCellSpacingSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { int spacing = ((JSlider)e.getSource()).getValue(); tableView.setIntercellSpacing(new Dimension(spacing, spacing)); tableView.repaint(); } }); rowHeightSlider = new JSlider(JSlider.HORIZONTAL, 5, 100, INITIAL_ROWHEIGHT); rowHeightSlider.getAccessibleContext().setAccessibleName(getString("TableDemo.row_height")); rowHeightLabel.setLabelFor(rowHeightSlider); sliderPanel.add(rowHeightSlider); rowHeightSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { int height = ((JSlider)e.getSource()).getValue(); tableView.setRowHeight(height); tableView.repaint(); } }); // Show that spacing controls are related relatedComponents.removeAllElements(); relatedComponents.add(interCellSpacingSlider); relatedComponents.add(rowHeightSlider); buildAccessibleGroup(relatedComponents); // Create the table. tableAggregate = createTable(); getDemoPanel().add(tableAggregate, BorderLayout.CENTER); // ComboBox for selection modes. JPanel selectMode = new JPanel(); selectMode.setLayout(new BoxLayout(selectMode, BoxLayout.X_AXIS)); selectMode.setBorder(new TitledBorder(getString("TableDemo.selection_mode"))); selectionModeComboBox = new JComboBox<>() { public Dimension getMaximumSize() { return getPreferredSize(); } }; selectionModeComboBox.addItem(getString("TableDemo.single")); selectionModeComboBox.addItem(getString("TableDemo.one_range")); selectionModeComboBox.addItem(getString("TableDemo.multiple_ranges")); selectionModeComboBox.setSelectedIndex(tableView.getSelectionModel().getSelectionMode()); selectionModeComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { JComboBox<?> source = (JComboBox<?>)e.getSource(); tableView.setSelectionMode(source.getSelectedIndex()); } }); selectMode.add(Box.createHorizontalStrut(2)); selectMode.add(selectionModeComboBox); selectMode.add(Box.createHorizontalGlue()); comboPanel.add(selectMode); // Combo box for table resize mode. JPanel resizeMode = new JPanel(); resizeMode.setLayout(new BoxLayout(resizeMode, BoxLayout.X_AXIS)); resizeMode.setBorder(new TitledBorder(getString("TableDemo.autoresize_mode"))); resizeModeComboBox = new JComboBox<>() { public Dimension getMaximumSize() { return getPreferredSize(); } }; resizeModeComboBox.addItem(getString("TableDemo.off")); resizeModeComboBox.addItem(getString("TableDemo.column_boundaries")); resizeModeComboBox.addItem(getString("TableDemo.subsequent_columns")); resizeModeComboBox.addItem(getString("TableDemo.last_column")); resizeModeComboBox.addItem(getString("TableDemo.all_columns")); resizeModeComboBox.setSelectedIndex(tableView.getAutoResizeMode()); resizeModeComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { JComboBox<?> source = (JComboBox<?>)e.getSource(); tableView.setAutoResizeMode(source.getSelectedIndex()); } }); resizeMode.add(Box.createHorizontalStrut(2)); resizeMode.add(resizeModeComboBox); resizeMode.add(Box.createHorizontalGlue()); comboPanel.add(resizeMode); // print panel printPanel.setBorder(new TitledBorder(getString("TableDemo.printing"))); headerLabel = new JLabel(getString("TableDemo.header")); footerLabel = new JLabel(getString("TableDemo.footer")); headerTextField = new JTextField(getString("TableDemo.headerText"), 15); footerTextField = new JTextField(getString("TableDemo.footerText"), 15); fitWidth = new JCheckBox(getString("TableDemo.fitWidth"), true); printButton = new JButton(getString("TableDemo.print")); printButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { printTable(); } }); printPanel.add(headerLabel); printPanel.add(headerTextField); printPanel.add(footerLabel); printPanel.add(footerTextField); JPanel buttons = new JPanel(); buttons.add(fitWidth); buttons.add(printButton); printPanel.add(buttons); // Show that printing controls are related relatedComponents.removeAllElements(); relatedComponents.add(headerTextField); relatedComponents.add(footerTextField); relatedComponents.add(printButton); buildAccessibleGroup(relatedComponents); // wrap up the panels and add them JPanel sliderWrapper = new JPanel(); sliderWrapper.setLayout(new BoxLayout(sliderWrapper, BoxLayout.X_AXIS)); sliderWrapper.add(labelPanel); sliderWrapper.add(sliderPanel); sliderWrapper.add(Box.createHorizontalGlue()); sliderWrapper.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0)); JPanel leftWrapper = new JPanel(); leftWrapper.setLayout(new BoxLayout(leftWrapper, BoxLayout.Y_AXIS)); leftWrapper.add(cbPanel); leftWrapper.add(sliderWrapper); // add everything controlPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 2, 0)); controlPanel.add(leftWrapper); controlPanel.add(comboPanel); controlPanel.add(printPanel); setTableControllers(); // Set accessibility information getDemoPanel().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) .put(KeyStroke.getKeyStroke("ctrl P"), "print"); getDemoPanel().getActionMap().put("print", new AbstractAction() { public void actionPerformed(ActionEvent ae) { printTable(); } }); } // TableDemo() /** * Sets the Accessibility MEMBER_OF property to denote that * these components work together as a group. Each object * is set to be a MEMBER_OF an array that contains all of * the objects in the group, including itself. * * @param components The list of objects that are related */ void buildAccessibleGroup(Vector<JComponent> components) { AccessibleContext context = null; int numComponents = components.size(); Object[] group = components.toArray(); Object object = null; for (int i = 0; i < numComponents; ++i) { object = components.elementAt(i); if (object instanceof Accessible) { context = ((Accessible)components.elementAt(i)). getAccessibleContext(); context.getAccessibleRelationSet().add( new AccessibleRelation( AccessibleRelation.MEMBER_OF, group)); } } } // buildAccessibleGroup() /** * This sets CONTROLLER_FOR on the controls that manipulate the * table and CONTROLLED_BY relationships on the table to point * back to the controllers. */ private void setTableControllers() { // Set up the relationships to show what controls the table setAccessibleController(isColumnReorderingAllowedCheckBox, tableAggregate); setAccessibleController(showHorizontalLinesCheckBox, tableAggregate); setAccessibleController(showVerticalLinesCheckBox, tableAggregate); setAccessibleController(isColumnSelectionAllowedCheckBox, tableAggregate); setAccessibleController(isRowSelectionAllowedCheckBox, tableAggregate); setAccessibleController(interCellSpacingSlider, tableAggregate); setAccessibleController(rowHeightSlider, tableAggregate); setAccessibleController(selectionModeComboBox, tableAggregate); setAccessibleController(resizeModeComboBox, tableAggregate); } // setTableControllers() /** * Sets up accessibility relationships to denote that one * object controls another. The CONTROLLER_FOR property is * set on the controller object, and the CONTROLLED_BY * property is set on the target object. */ private void setAccessibleController(JComponent controller, JComponent target) { AccessibleRelationSet controllerRelations = controller.getAccessibleContext().getAccessibleRelationSet(); AccessibleRelationSet targetRelations = target.getAccessibleContext().getAccessibleRelationSet(); controllerRelations.add( new AccessibleRelation( AccessibleRelation.CONTROLLER_FOR, target)); targetRelations.add( new AccessibleRelation( AccessibleRelation.CONTROLLED_BY, controller)); } // setAccessibleController() public JScrollPane createTable() { // final final String[] names = { getString("TableDemo.first_name"), getString("TableDemo.last_name"), getString("TableDemo.favorite_color"), getString("TableDemo.favorite_movie"), getString("TableDemo.favorite_number"), getString("TableDemo.favorite_food") }; ImageIcon apple = createImageIcon("food/apple.jpg", getString("TableDemo.apple")); ImageIcon asparagus = createImageIcon("food/asparagus.gif", getString("TableDemo.asparagus")); ImageIcon banana = createImageIcon("food/banana.gif", getString("TableDemo.banana")); ImageIcon broccoli = createImageIcon("food/broccoli.gif", getString("TableDemo.broccoli")); ImageIcon cantaloupe = createImageIcon("food/cantaloupe.gif", getString("TableDemo.cantaloupe")); ImageIcon carrot = createImageIcon("food/carrot.gif", getString("TableDemo.carrot")); ImageIcon corn = createImageIcon("food/corn.gif", getString("TableDemo.corn")); ImageIcon grapes = createImageIcon("food/grapes.gif", getString("TableDemo.grapes")); ImageIcon grapefruit = createImageIcon("food/grapefruit.gif", getString("TableDemo.grapefruit")); ImageIcon kiwi = createImageIcon("food/kiwi.gif", getString("TableDemo.kiwi")); ImageIcon onion = createImageIcon("food/onion.gif", getString("TableDemo.onion")); ImageIcon pear = createImageIcon("food/pear.gif", getString("TableDemo.pear")); ImageIcon peach = createImageIcon("food/peach.gif", getString("TableDemo.peach")); ImageIcon pepper = createImageIcon("food/pepper.gif", getString("TableDemo.pepper")); ImageIcon pickle = createImageIcon("food/pickle.gif", getString("TableDemo.pickle")); ImageIcon pineapple = createImageIcon("food/pineapple.gif", getString("TableDemo.pineapple")); ImageIcon raspberry = createImageIcon("food/raspberry.gif", getString("TableDemo.raspberry")); ImageIcon sparegrass = createImageIcon("food/asparagus.gif", getString("TableDemo.sparegrass")); ImageIcon strawberry = createImageIcon("food/strawberry.gif", getString("TableDemo.strawberry")); ImageIcon tomato = createImageIcon("food/tomato.gif", getString("TableDemo.tomato")); ImageIcon watermelon = createImageIcon("food/watermelon.gif", getString("TableDemo.watermelon")); NamedColor aqua = new NamedColor(new Color(127, 255, 212), getString("TableDemo.aqua")); NamedColor beige = new NamedColor(new Color(245, 245, 220), getString("TableDemo.beige")); NamedColor black = new NamedColor(Color.black, getString("TableDemo.black")); NamedColor blue = new NamedColor(new Color(0, 0, 222), getString("TableDemo.blue")); NamedColor eblue = new NamedColor(Color.blue, getString("TableDemo.eblue")); NamedColor jfcblue = new NamedColor(new Color(204, 204, 255), getString("TableDemo.jfcblue")); NamedColor jfcblue2 = new NamedColor(new Color(153, 153, 204), getString("TableDemo.jfcblue2")); NamedColor cybergreen = new NamedColor(Color.green.darker().brighter(), getString("TableDemo.cybergreen")); NamedColor darkgreen = new NamedColor(new Color(0, 100, 75), getString("TableDemo.darkgreen")); NamedColor forestgreen = new NamedColor(Color.green.darker(), getString("TableDemo.forestgreen")); NamedColor gray = new NamedColor(Color.gray, getString("TableDemo.gray")); NamedColor green = new NamedColor(Color.green, getString("TableDemo.green")); NamedColor orange = new NamedColor(new Color(255, 165, 0), getString("TableDemo.orange")); NamedColor purple = new NamedColor(new Color(160, 32, 240), getString("TableDemo.purple")); NamedColor red = new NamedColor(Color.red, getString("TableDemo.red")); NamedColor rustred = new NamedColor(Color.red.darker(), getString("TableDemo.rustred")); NamedColor sunpurple = new NamedColor(new Color(100, 100, 255), getString("TableDemo.sunpurple")); NamedColor suspectpink = new NamedColor(new Color(255, 105, 180), getString("TableDemo.suspectpink")); NamedColor turquoise = new NamedColor(new Color(0, 255, 255), getString("TableDemo.turquoise")); NamedColor violet = new NamedColor(new Color(238, 130, 238), getString("TableDemo.violet")); NamedColor yellow = new NamedColor(Color.yellow, getString("TableDemo.yellow")); // Create the dummy data (a few rows of names) final Object[][] data = { {"Mike", "Albers", green, getString("TableDemo.brazil"), Double.valueOf(44.0), strawberry}, {"Mark", "Andrews", blue, getString("TableDemo.curse"), Double.valueOf(3), grapes}, {"Brian", "Beck", black, getString("TableDemo.bluesbros"), Double.valueOf(2.7182818285), raspberry}, {"Lara", "Bunni", red, getString("TableDemo.airplane"), Double.valueOf(15), strawberry}, {"Roger", "Brinkley", blue, getString("TableDemo.man"), Double.valueOf(13), peach}, {"Brent", "Christian", black, getString("TableDemo.bladerunner"), Double.valueOf(23), broccoli}, {"Mark", "Davidson", darkgreen, getString("TableDemo.brazil"), Double.valueOf(27), asparagus}, {"Jeff", "Dinkins", blue, getString("TableDemo.ladyvanishes"), Double.valueOf(8), kiwi}, {"Ewan", "Dinkins", yellow, getString("TableDemo.bugs"), Double.valueOf(2), strawberry}, {"Amy", "Fowler", violet, getString("TableDemo.reservoir"), Double.valueOf(3), raspberry}, {"Hania", "Gajewska", purple, getString("TableDemo.jules"), Double.valueOf(5), raspberry}, {"David", "Geary", blue, getString("TableDemo.pulpfiction"), Double.valueOf(3), watermelon}, // {"James", "Gosling", pink, getString("TableDemo.tennis"), Double.valueOf(21), donut}, {"Eric", "Hawkes", blue, getString("TableDemo.bladerunner"), Double.valueOf(.693), pickle}, {"Shannon", "Hickey", green, getString("TableDemo.shawshank"), Double.valueOf(2), grapes}, {"Earl", "Johnson", green, getString("TableDemo.pulpfiction"), Double.valueOf(8), carrot}, {"Robi", "Khan", green, getString("TableDemo.goodfellas"), Double.valueOf(89), apple}, {"Robert", "Kim", blue, getString("TableDemo.mohicans"), Double.valueOf(655321), strawberry}, {"Janet", "Koenig", turquoise, getString("TableDemo.lonestar"), Double.valueOf(7), peach}, {"Jeff", "Kesselman", blue, getString("TableDemo.stuntman"), Double.valueOf(17), pineapple}, {"Onno", "Kluyt", orange, getString("TableDemo.oncewest"), Double.valueOf(8), broccoli}, {"Peter", "Korn", sunpurple, getString("TableDemo.musicman"), Double.valueOf(12), sparegrass}, {"Rick", "Levenson", black, getString("TableDemo.harold"), Double.valueOf(1327), raspberry}, {"Brian", "Lichtenwalter", jfcblue, getString("TableDemo.fifthelement"), Double.valueOf(22), pear}, {"Malini", "Minasandram", beige, getString("TableDemo.joyluck"), Double.valueOf(9), corn}, {"Michael", "Martak", green, getString("TableDemo.city"), Double.valueOf(3), strawberry}, {"David", "Mendenhall", forestgreen, getString("TableDemo.schindlerslist"), Double.valueOf(7), peach}, {"Phil", "Milne", suspectpink, getString("TableDemo.withnail"), Double.valueOf(3), banana}, {"Lynn", "Monsanto", cybergreen, getString("TableDemo.dasboot"), Double.valueOf(52), peach}, {"Hans", "Muller", rustred, getString("TableDemo.eraserhead"), Double.valueOf(0), pineapple}, {"Joshua", "Outwater", blue, getString("TableDemo.labyrinth"), Double.valueOf(3), pineapple}, {"Tim", "Prinzing", blue, getString("TableDemo.firstsight"), Double.valueOf(69), pepper}, {"Raj", "Premkumar", jfcblue2, getString("TableDemo.none"), Double.valueOf(7), broccoli}, {"Howard", "Rosen", green, getString("TableDemo.defending"), Double.valueOf(7), strawberry}, {"Ray", "Ryan", black, getString("TableDemo.buckaroo"), Double.valueOf(3.141592653589793238462643383279502884197169399375105820974944), banana}, {"Georges", "Saab", aqua, getString("TableDemo.bicycle"), Double.valueOf(290), cantaloupe}, {"Tom", "Santos", blue, getString("TableDemo.spinaltap"), Double.valueOf(241), pepper}, {"Rich", "Schiavi", blue, getString("TableDemo.repoman"), Double.valueOf(0xFF), pepper}, {"Nancy", "Schorr", green, getString("TableDemo.fifthelement"), Double.valueOf(47), watermelon}, {"Keith", "Sprochi", darkgreen, getString("TableDemo.2001"), Double.valueOf(13), watermelon}, {"Matt", "Tucker", eblue, getString("TableDemo.starwars"), Double.valueOf(2), broccoli}, {"Dmitri", "Trembovetski", red, getString("TableDemo.aliens"), Double.valueOf(222), tomato}, {"Scott", "Violet", violet, getString("TableDemo.raiders"), Double.valueOf(-97), banana}, {"Kathy", "Walrath", darkgreen, getString("TableDemo.thinman"), Double.valueOf(8), pear}, {"Nathan", "Walrath", black, getString("TableDemo.chusingura"), Double.valueOf(3), grapefruit}, {"Steve", "Wilson", green, getString("TableDemo.raiders"), Double.valueOf(7), onion}, {"Kathleen", "Zelony", gray, getString("TableDemo.dog"), Double.valueOf(13), grapes} }; // Create a model of the data. TableModel dataModel = new AbstractTableModel() { public int getColumnCount() { return names.length; } public int getRowCount() { return data.length;} public Object getValueAt(int row, int col) {return data[row][col];} public String getColumnName(int column) {return names[column];} public Class<?> getColumnClass(int c) { Object obj = getValueAt(0, c); return obj != null ? obj.getClass() : Object.class; } public boolean isCellEditable(int row, int col) {return col != 5;} public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; } }; // Create the table tableView = new JTable(dataModel); TableRowSorter<TableModel> sorter = new TableRowSorter<>(dataModel); tableView.setRowSorter(sorter); // Show colors by rendering them in their own color. DefaultTableCellRenderer colorRenderer = new DefaultTableCellRenderer() { public void setValue(Object value) { if (value instanceof NamedColor) { NamedColor c = (NamedColor) value; setBackground(c); setForeground(c.getTextColor()); setText(c.toString()); } else { super.setValue(value); } } }; // Create a combo box to show that you can use one in a table. JComboBox<NamedColor> comboBox = new JComboBox<>(); comboBox.addItem(aqua); comboBox.addItem(beige); comboBox.addItem(black); comboBox.addItem(blue); comboBox.addItem(eblue); comboBox.addItem(jfcblue); comboBox.addItem(jfcblue2); comboBox.addItem(cybergreen); comboBox.addItem(darkgreen); comboBox.addItem(forestgreen); comboBox.addItem(gray); comboBox.addItem(green); comboBox.addItem(orange); comboBox.addItem(purple); comboBox.addItem(red); comboBox.addItem(rustred); comboBox.addItem(sunpurple); comboBox.addItem(suspectpink); comboBox.addItem(turquoise); comboBox.addItem(violet); comboBox.addItem(yellow); TableColumn colorColumn = tableView.getColumn(getString("TableDemo.favorite_color")); // Use the combo box as the editor in the "Favorite Color" column. colorColumn.setCellEditor(new DefaultCellEditor(comboBox)); colorRenderer.setHorizontalAlignment(JLabel.CENTER); colorColumn.setCellRenderer(colorRenderer); tableView.setRowHeight(INITIAL_ROWHEIGHT); scrollpane = new JScrollPane(tableView); return scrollpane; } private void printTable() { MessageFormat headerFmt; MessageFormat footerFmt; JTable.PrintMode printMode = fitWidth.isSelected() ? JTable.PrintMode.FIT_WIDTH : JTable.PrintMode.NORMAL; String text; text = headerTextField.getText(); if (text != null && text.length() > 0) { headerFmt = new MessageFormat(text); } else { headerFmt = null; } text = footerTextField.getText(); if (text != null && text.length() > 0) { footerFmt = new MessageFormat(text); } else { footerFmt = null; } try { boolean status = tableView.print(printMode, headerFmt, footerFmt); if (status) { JOptionPane.showMessageDialog(tableView.getParent(), getString("TableDemo.printingComplete"), getString("TableDemo.printingResult"), JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(tableView.getParent(), getString("TableDemo.printingCancelled"), getString("TableDemo.printingResult"), JOptionPane.INFORMATION_MESSAGE); } } catch (PrinterException pe) { String errorMessage = MessageFormat.format(getString("TableDemo.printingFailed"), new Object[] {pe.getMessage()}); JOptionPane.showMessageDialog(tableView.getParent(), errorMessage, getString("TableDemo.printingResult"), JOptionPane.ERROR_MESSAGE); } catch (SecurityException se) { String errorMessage = MessageFormat.format(getString("TableDemo.printingFailed"), new Object[] {se.getMessage()}); JOptionPane.showMessageDialog(tableView.getParent(), errorMessage, getString("TableDemo.printingResult"), JOptionPane.ERROR_MESSAGE); } } class NamedColor extends Color { String name; public NamedColor(Color color, String name) { super(color.getRGB()); this.name = name; } public Color getTextColor() { int r = getRed(); int g = getGreen(); int b = getBlue(); if(r > 240 || g > 240) { return Color.black; } else { return Color.white; } } public String toString() { return name; } } class ColumnLayout implements LayoutManager { int xInset = 5; int yInset = 5; int yGap = 2; public void addLayoutComponent(String s, Component c) {} public void layoutContainer(Container c) { Insets insets = c.getInsets(); int height = yInset + insets.top; Component[] children = c.getComponents(); Dimension compSize = null; for (int i = 0; i < children.length; i++) { compSize = children[i].getPreferredSize(); children[i].setSize(compSize.width, compSize.height); children[i].setLocation( xInset + insets.left, height); height += compSize.height + yGap; } } public Dimension minimumLayoutSize(Container c) { Insets insets = c.getInsets(); int height = yInset + insets.top; int width = 0 + insets.left + insets.right; Component[] children = c.getComponents(); Dimension compSize = null; for (int i = 0; i < children.length; i++) { compSize = children[i].getPreferredSize(); height += compSize.height + yGap; width = Math.max(width, compSize.width + insets.left + insets.right + xInset*2); } height += insets.bottom; return new Dimension( width, height); } public Dimension preferredLayoutSize(Container c) { return minimumLayoutSize(c); } public void removeLayoutComponent(Component c) {} } void updateDragEnabled(boolean dragEnabled) { tableView.setDragEnabled(dragEnabled); headerTextField.setDragEnabled(dragEnabled); footerTextField.setDragEnabled(dragEnabled); } }
Hamzablm/jdk
src/demo/share/jfc/SwingSet2/TableDemo.java
213,994
/* * Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. All rights reserved. * * 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.didi.virtualapk.delegate; import android.app.ActivityManagerNative; import android.app.IActivityManager; import android.app.IApplicationThread; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.os.Bundle; import android.os.DeadObjectException; import android.os.IBinder; import android.os.RemoteException; import android.os.ServiceManager; import android.util.Log; import com.didi.virtualapk.PluginManager; import com.didi.virtualapk.internal.Constants; import com.didi.virtualapk.internal.utils.PluginUtil; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * @author johnsonlee */ public class ActivityManagerProxy implements InvocationHandler { private static final String TAG = Constants.TAG_PREFIX + "IActivityManagerProxy"; public static final int INTENT_SENDER_BROADCAST = 1; public static final int INTENT_SENDER_ACTIVITY = 2; public static final int INTENT_SENDER_ACTIVITY_RESULT = 3; public static final int INTENT_SENDER_SERVICE = 4; private PluginManager mPluginManager; private IActivityManager mActivityManager; public ActivityManagerProxy(PluginManager pluginManager, IActivityManager activityManager) { this.mPluginManager = pluginManager; this.mActivityManager = activityManager; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("startService".equals(method.getName())) { try { return startService(proxy, method, args); } catch (Throwable e) { Log.e(TAG, "Start service error", e); } } else if ("stopService".equals(method.getName())) { try { return stopService(proxy, method, args); } catch (Throwable e) { Log.e(TAG, "Stop Service error", e); } } else if ("stopServiceToken".equals(method.getName())) { try { return stopServiceToken(proxy, method, args); } catch (Throwable e) { Log.e(TAG, "Stop service token error", e); } } else if ("bindService".equals(method.getName())) { try { return bindService(proxy, method, args); } catch (Throwable e) { Log.w(TAG, e); } } else if ("unbindService".equals(method.getName())) { try { return unbindService(proxy, method, args); } catch (Throwable e) { Log.w(TAG, e); } } else if ("getIntentSender".equals(method.getName())) { try { getIntentSender(method, args); } catch (Exception e) { Log.w(TAG, e); } } else if ("overridePendingTransition".equals(method.getName())){ try { overridePendingTransition(method, args); } catch (Exception e){ Log.w(TAG, e); } } try { // sometimes system binder has problems. return method.invoke(this.mActivityManager, args); } catch (Throwable th) { Throwable c = th.getCause(); if (c != null && c instanceof DeadObjectException) { // retry connect to system binder IBinder ams = ServiceManager.getService(Context.ACTIVITY_SERVICE); if (ams != null) { IActivityManager am = ActivityManagerNative.asInterface(ams); mActivityManager = am; } } Throwable cause = th; do { if (cause instanceof RemoteException) { throw cause; } } while ((cause = cause.getCause()) != null); throw c != null ? c : th; } } protected Object startService(Object proxy, Method method, Object[] args) throws Throwable { IApplicationThread appThread = (IApplicationThread) args[0]; Intent target = (Intent) args[1]; ResolveInfo resolveInfo = this.mPluginManager.resolveService(target, 0); if (null == resolveInfo || null == resolveInfo.serviceInfo) { // is host service return method.invoke(this.mActivityManager, args); } return startDelegateServiceForTarget(target, resolveInfo.serviceInfo, null, RemoteService.EXTRA_COMMAND_START_SERVICE); } protected Object stopService(Object proxy, Method method, Object[] args) throws Throwable { Intent target = (Intent) args[1]; ResolveInfo resolveInfo = this.mPluginManager.resolveService(target, 0); if (null == resolveInfo || null == resolveInfo.serviceInfo) { // is hot service return method.invoke(this.mActivityManager, args); } startDelegateServiceForTarget(target, resolveInfo.serviceInfo, null, RemoteService.EXTRA_COMMAND_STOP_SERVICE); return 1; } protected Object stopServiceToken(Object proxy, Method method, Object[] args) throws Throwable { ComponentName component = (ComponentName) args[0]; Intent target = new Intent().setComponent(component); ResolveInfo resolveInfo = this.mPluginManager.resolveService(target, 0); if (null == resolveInfo || null == resolveInfo.serviceInfo) { // is hot service return method.invoke(this.mActivityManager, args); } startDelegateServiceForTarget(target, resolveInfo.serviceInfo, null, RemoteService.EXTRA_COMMAND_STOP_SERVICE); return true; } protected Object bindService(Object proxy, Method method, Object[] args) throws Throwable { Intent target = (Intent) args[2]; ResolveInfo resolveInfo = this.mPluginManager.resolveService(target, 0); if (null == resolveInfo || null == resolveInfo.serviceInfo) { // is host service return method.invoke(this.mActivityManager, args); } Bundle bundle = new Bundle(); PluginUtil.putBinder(bundle, "sc", (IBinder) args[4]); startDelegateServiceForTarget(target, resolveInfo.serviceInfo, bundle, RemoteService.EXTRA_COMMAND_BIND_SERVICE); mPluginManager.getComponentsHandler().remberIServiceConnection((IBinder) args[4], target); return 1; } protected Object unbindService(Object proxy, Method method, Object[] args) throws Throwable { IBinder iServiceConnection = (IBinder)args[0]; Intent target = mPluginManager.getComponentsHandler().forgetIServiceConnection(iServiceConnection); if (target == null) { // is host service return method.invoke(this.mActivityManager, args); } ResolveInfo resolveInfo = this.mPluginManager.resolveService(target, 0); startDelegateServiceForTarget(target, resolveInfo.serviceInfo, null, RemoteService.EXTRA_COMMAND_UNBIND_SERVICE); return true; } protected ComponentName startDelegateServiceForTarget(Intent target, ServiceInfo serviceInfo, Bundle extras, int command) { Intent wrapperIntent = wrapperTargetIntent(target, serviceInfo, extras, command); return mPluginManager.getHostContext().startService(wrapperIntent); } protected Intent wrapperTargetIntent(Intent target, ServiceInfo serviceInfo, Bundle extras, int command) { // fill in service with ComponentName target.setComponent(new ComponentName(serviceInfo.packageName, serviceInfo.name)); String pluginLocation = mPluginManager.getLoadedPlugin(target.getComponent()).getLocation(); // start delegate service to run plugin service inside boolean local = PluginUtil.isLocalService(serviceInfo); Class<? extends Service> delegate = local ? LocalService.class : RemoteService.class; Intent intent = new Intent(); intent.setClass(mPluginManager.getHostContext(), delegate); intent.putExtra(RemoteService.EXTRA_TARGET, target); intent.putExtra(RemoteService.EXTRA_COMMAND, command); intent.putExtra(RemoteService.EXTRA_PLUGIN_LOCATION, pluginLocation); if (extras != null) { intent.putExtras(extras); } return intent; } protected void getIntentSender(Method method, Object[] args) { String hostPackageName = mPluginManager.getHostContext().getPackageName(); args[1] = hostPackageName; Intent target = ((Intent[]) args[5])[0]; int intentSenderType = (int)args[0]; if (intentSenderType == INTENT_SENDER_ACTIVITY) { mPluginManager.getComponentsHandler().transformIntentToExplicitAsNeeded(target); mPluginManager.getComponentsHandler().markIntentIfNeeded(target); } else if (intentSenderType == INTENT_SENDER_SERVICE) { ResolveInfo resolveInfo = this.mPluginManager.resolveService(target, 0); if (resolveInfo != null && resolveInfo.serviceInfo != null) { // find plugin service Intent wrapperIntent = wrapperTargetIntent(target, resolveInfo.serviceInfo, null, RemoteService.EXTRA_COMMAND_START_SERVICE); ((Intent[]) args[5])[0] = wrapperIntent; } } else if (intentSenderType == INTENT_SENDER_BROADCAST) { // no action } } protected void overridePendingTransition(Method method, Object[] args) { String hostPackageName = mPluginManager.getHostContext().getPackageName(); args[1] = hostPackageName; } }
didi/VirtualAPK
CoreLibrary/src/main/java/com/didi/virtualapk/delegate/ActivityManagerProxy.java
213,995
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory; /** * Interface to be implemented by objects used within a {@link BeanFactory} * which are themselves factories. If a bean implements this interface, * it is used as a factory for an object to expose, not directly as a bean * instance that will be exposed itself. * * <p><b>NB: A bean that implements this interface cannot be used as a * normal bean.</b> A FactoryBean is defined in a bean style, but the * object exposed for bean references ({@link #getObject()} is always * the object that it creates. * * <p>FactoryBeans can support singletons and prototypes, and can * either create objects lazily on demand or eagerly on startup. * The {@link SmartFactoryBean} interface allows for exposing * more fine-grained behavioral metadata. * * <p>This interface is heavily used within the framework itself, for * example for the AOP {@link org.springframework.aop.framework.ProxyFactoryBean} * or the {@link org.springframework.jndi.JndiObjectFactoryBean}. * It can be used for application components as well; however, * this is not common outside of infrastructure code. * * <p><b>NOTE:</b> FactoryBean objects participate in the containing * BeanFactory's synchronization of bean creation. There is usually no * need for internal synchronization other than for purposes of lazy * initialization within the FactoryBean itself (or the like). * * @author Rod Johnson * @author Juergen Hoeller * @since 08.03.2003 * @see BeanFactory * @see org.springframework.aop.framework.ProxyFactoryBean * @see org.springframework.jndi.JndiObjectFactoryBean */ public interface FactoryBean<T> { /** * Return an instance (possibly shared or independent) of the object * managed by this factory. * <p>As with a {@link BeanFactory}, this allows support for both the * Singleton and Prototype design pattern. * <p>If this FactoryBean is not fully initialized yet at the time of * the call (for example because it is involved in a circular reference), * throw a corresponding {@link FactoryBeanNotInitializedException}. * <p>As of Spring 2.0, FactoryBeans are allowed to return {@code null} * objects. The factory will consider this as normal value to be used; it * will not throw a FactoryBeanNotInitializedException in this case anymore. * FactoryBean implementations are encouraged to throw * FactoryBeanNotInitializedException themselves now, as appropriate. * @return an instance of the bean (can be {@code null}) * @throws Exception in case of creation errors * @see FactoryBeanNotInitializedException */ T getObject() throws Exception; /** * Return the type of object that this FactoryBean creates, * or {@code null} if not known in advance. * <p>This allows one to check for specific types of beans without * instantiating objects, for example on autowiring. * <p>In the case of implementations that are creating a singleton object, * this method should try to avoid singleton creation as far as possible; * it should rather estimate the type in advance. * For prototypes, returning a meaningful type here is advisable too. * <p>This method can be called <i>before</i> this FactoryBean has * been fully initialized. It must not rely on state created during * initialization; of course, it can still use such state if available. * <p><b>NOTE:</b> Autowiring will simply ignore FactoryBeans that return * {@code null} here. Therefore it is highly recommended to implement * this method properly, using the current state of the FactoryBean. * @return the type of object that this FactoryBean creates, * or {@code null} if not known at the time of the call * @see ListableBeanFactory#getBeansOfType */ Class<?> getObjectType(); /** * Is the object managed by this factory a singleton? That is, * will {@link #getObject()} always return the same object * (a reference that can be cached)? * <p><b>NOTE:</b> If a FactoryBean indicates to hold a singleton object, * the object returned from {@code getObject()} might get cached * by the owning BeanFactory. Hence, do not return {@code true} * unless the FactoryBean always exposes the same reference. * <p>The singleton status of the FactoryBean itself will generally * be provided by the owning BeanFactory; usually, it has to be * defined as singleton there. * <p><b>NOTE:</b> This method returning {@code false} does not * necessarily indicate that returned objects are independent instances. * An implementation of the extended {@link SmartFactoryBean} interface * may explicitly indicate independent instances through its * {@link SmartFactoryBean#isPrototype()} method. Plain {@link FactoryBean} * implementations which do not implement this extended interface are * simply assumed to always return independent instances if the * {@code isSingleton()} implementation returns {@code false}. * @return whether the exposed object is a singleton * @see #getObject() * @see SmartFactoryBean#isPrototype() */ boolean isSingleton(); }
jinchihe/blog_demos
springbeans_modify/src/main/java/org/springframework/beans/factory/FactoryBean.java
213,996
package models; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import utility.FuncUtils; import utility.LBFGS; import utility.Parallel; import cc.mallet.optimize.InvalidOptimizableException; import cc.mallet.optimize.Optimizer; import cc.mallet.types.MatrixOps; import cc.mallet.util.Randoms; /** * Implementation of the LF-DMM latent feature topic model, using collapsed * Gibbs sampling, as described in: * * Dat Quoc Nguyen, Richard Billingsley, Lan Du and Mark Johnson. 2015. * Improving Topic Models with Latent Feature Word Representations. Transactions * of the Association for Computational Linguistics, vol. 3, pp. 299-313. * * Inference of topic distribution on unseen corpus * * @author Dat Quoc Nguyen */ public class LFDMM_Inf { public double alpha; // Hyper-parameter alpha public double beta; // Hyper-parameter alpha // public double alphaSum; // alpha * numTopics public double betaSum; // beta * vocabularySize public int numTopics; // Number of topics public int topWords; // Number of most probable words for each topic public double lambda; // Mixture weight value public int numInitIterations; public int numIterations; // Number of EM-style sampling iterations public List<List<Integer>> corpus; // Word ID-based corpus public List<List<Integer>> topicAssignments; // Topics assignments for words // in the corpus public int numDocuments; // Number of documents in the corpus public int numWordsInCorpus; // Number of words in the corpus public HashMap<String, Integer> word2IdVocabulary; // Vocabulary to get ID // given a word public HashMap<Integer, String> id2WordVocabulary; // Vocabulary to get word // given an ID public int vocabularySize; // The number of word types in the corpus // Number of documents assigned to a topic public int[] docTopicCount; // numTopics * vocabularySize matrix // Given a topic: number of times a word type generated from the topic by // the Dirichlet multinomial component public int[][] topicWordCountDMM; // Total number of words generated from each topic by the Dirichlet // multinomial component public int[] sumTopicWordCountDMM; // numTopics * vocabularySize matrix // Given a topic: number of times a word type generated from the topic by // the latent feature component public int[][] topicWordCountLF; // Total number of words generated from each topic by the latent feature // component public int[] sumTopicWordCountLF; // Double array used to sample a topic public double[] multiPros; // Path to the directory containing the corpus public String folderPath; // Path to the topic modeling corpus public String corpusPath; public String vectorFilePath; public double[][] wordVectors; // Vector representations for words public double[][] topicVectors;// Vector representations for topics public int vectorSize; // Number of vector dimensions public double[][] dotProductValues; public double[][] expDotProductValues; public double[] sumExpValues; // Partition function values public final double l2Regularizer = 0.01; // L2 regularizer value for // learning topic vectors public final double tolerance = 0.05; // Tolerance value for LBFGS // convergence public String expName = "LFDMMinf"; public String orgExpName = "LFDMMinf"; public int savestep = 0; public LFDMM_Inf(String pathToTrainingParasFile, String pathToUnseenCorpus, int inNumInitIterations, int inNumIterations, int inTopWords, String inExpName, int inSaveStep) throws Exception { HashMap<String, String> paras = parseTrainingParasFile(pathToTrainingParasFile); if (!paras.get("-model").equals("LFDMM")) { throw new Exception("Wrong pre-trained model!!!"); } alpha = new Double(paras.get("-alpha")); beta = new Double(paras.get("-beta")); lambda = new Double(paras.get("-lambda")); numTopics = new Integer(paras.get("-ntopics")); numIterations = inNumIterations; numInitIterations = inNumInitIterations; topWords = inTopWords; savestep = inSaveStep; expName = inExpName; orgExpName = expName; vectorFilePath = paras.get("-vectors"); String trainingCorpus = paras.get("-corpus"); String trainingCorpusfolder = trainingCorpus.substring( 0, Math.max(trainingCorpus.lastIndexOf("/"), trainingCorpus.lastIndexOf("\\")) + 1); String topicAssignment4TrainFile = trainingCorpusfolder + paras.get("-name") + ".topicAssignments"; word2IdVocabulary = new HashMap<String, Integer>(); id2WordVocabulary = new HashMap<Integer, String>(); initializeWordCount(trainingCorpus, topicAssignment4TrainFile); corpusPath = pathToUnseenCorpus; folderPath = pathToUnseenCorpus.substring( 0, Math.max(pathToUnseenCorpus.lastIndexOf("/"), pathToUnseenCorpus.lastIndexOf("\\")) + 1); System.out.println("Reading unseen corpus: " + pathToUnseenCorpus); corpus = new ArrayList<List<Integer>>(); numDocuments = 0; numWordsInCorpus = 0; BufferedReader br = null; try { br = new BufferedReader(new FileReader(pathToUnseenCorpus)); for (String doc; (doc = br.readLine()) != null;) { if (doc.trim().length() == 0) continue; String[] words = doc.trim().split("\\s+"); List<Integer> document = new ArrayList<Integer>(); for (String word : words) { if (word2IdVocabulary.containsKey(word)) { document.add(word2IdVocabulary.get(word)); } else { // Skip this unknown-word } } numDocuments++; numWordsInCorpus += document.size(); corpus.add(document); } } catch (Exception e) { e.printStackTrace(); } docTopicCount = new int[numTopics]; multiPros = new double[numTopics]; for (int i = 0; i < numTopics; i++) { multiPros[i] = 1.0 / numTopics; } // alphaSum = numTopics * alpha; betaSum = vocabularySize * beta; readWordVectorsFile(vectorFilePath); topicVectors = new double[numTopics][vectorSize]; dotProductValues = new double[numTopics][vocabularySize]; expDotProductValues = new double[numTopics][vocabularySize]; sumExpValues = new double[numTopics]; System.out.println("Corpus size: " + numDocuments + " docs, " + numWordsInCorpus + " words"); System.out.println("Vocabuary size: " + vocabularySize); System.out.println("Number of topics: " + numTopics); System.out.println("alpha: " + alpha); System.out.println("beta: " + beta); System.out.println("lambda: " + lambda); System.out.println("Number of initial sampling iterations: " + numInitIterations); System.out .println("Number of EM-style sampling iterations for the LF-DMM model: " + numIterations); System.out.println("Number of top topical words: " + topWords); initialize(); } private HashMap<String, String> parseTrainingParasFile( String pathToTrainingParasFile) throws Exception { HashMap<String, String> paras = new HashMap<String, String>(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(pathToTrainingParasFile)); for (String line; (line = br.readLine()) != null;) { if (line.trim().length() == 0) continue; String[] paraOptions = line.trim().split("\\s+"); paras.put(paraOptions[0], paraOptions[1]); } } catch (Exception e) { e.printStackTrace(); } return paras; } private void initializeWordCount(String pathToTrainingCorpus, String pathToTopicAssignmentFile) { System.out.println("Loading pre-trained model..."); List<List<Integer>> trainCorpus = new ArrayList<List<Integer>>(); BufferedReader br = null; try { int indexWord = -1; br = new BufferedReader(new FileReader(pathToTrainingCorpus)); for (String doc; (doc = br.readLine()) != null;) { if (doc.trim().length() == 0) continue; String[] words = doc.trim().split("\\s+"); List<Integer> document = new ArrayList<Integer>(); for (String word : words) { if (word2IdVocabulary.containsKey(word)) { document.add(word2IdVocabulary.get(word)); } else { indexWord += 1; word2IdVocabulary.put(word, indexWord); id2WordVocabulary.put(indexWord, word); document.add(indexWord); } } trainCorpus.add(document); } } catch (Exception e) { e.printStackTrace(); } vocabularySize = word2IdVocabulary.size(); topicWordCountDMM = new int[numTopics][vocabularySize]; sumTopicWordCountDMM = new int[numTopics]; topicWordCountLF = new int[numTopics][vocabularySize]; sumTopicWordCountLF = new int[numTopics]; try { br = new BufferedReader(new FileReader(pathToTopicAssignmentFile)); int docId = 0; for (String line; (line = br.readLine()) != null;) { String[] strTopics = line.trim().split("\\s+"); int topic = new Integer(strTopics[0]) % numTopics; for (int j = 0; j < strTopics.length; j++) { int wordId = trainCorpus.get(docId).get(j); int subtopic = new Integer(strTopics[j]); if (subtopic == topic) { topicWordCountLF[topic][wordId] += 1; sumTopicWordCountLF[topic] += 1; } else { topicWordCountDMM[topic][wordId] += 1; sumTopicWordCountDMM[topic] += 1; } } docId++; } } catch (Exception e) { e.printStackTrace(); } } public void readWordVectorsFile(String pathToWordVectorsFile) throws Exception { System.out.println("Reading word vectors from word-vectors file " + pathToWordVectorsFile + "..."); BufferedReader br = null; try { br = new BufferedReader(new FileReader(pathToWordVectorsFile)); String[] elements = br.readLine().trim().split("\\s+"); vectorSize = elements.length - 1; wordVectors = new double[vocabularySize][vectorSize]; String word = elements[0]; if (word2IdVocabulary.containsKey(word)) { for (int j = 0; j < vectorSize; j++) { wordVectors[word2IdVocabulary.get(word)][j] = new Double( elements[j + 1]); } } for (String line; (line = br.readLine()) != null;) { elements = line.trim().split("\\s+"); word = elements[0]; if (word2IdVocabulary.containsKey(word)) { for (int j = 0; j < vectorSize; j++) { wordVectors[word2IdVocabulary.get(word)][j] = new Double( elements[j + 1]); } } } } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < vocabularySize; i++) { if (MatrixOps.absNorm(wordVectors[i]) == 0.0) { System.out.println("The word \"" + id2WordVocabulary.get(i) + "\" doesn't have a corresponding vector!!!"); throw new Exception(); } } } public void initialize() throws IOException { System.out.println("Randomly initialzing topic assignments ..."); topicAssignments = new ArrayList<List<Integer>>(); for (int docId = 0; docId < numDocuments; docId++) { List<Integer> topics = new ArrayList<Integer>(); int topic = FuncUtils.nextDiscrete(multiPros); docTopicCount[topic] += 1; int docSize = corpus.get(docId).size(); for (int j = 0; j < docSize; j++) { int wordId = corpus.get(docId).get(j); boolean component = new Randoms().nextBoolean(); int subtopic = topic; if (!component) { // Generated from the latent feature component topicWordCountLF[topic][wordId] += 1; sumTopicWordCountLF[topic] += 1; } else {// Generated from the Dirichlet multinomial component topicWordCountDMM[topic][wordId] += 1; sumTopicWordCountDMM[topic] += 1; subtopic = subtopic + numTopics; } topics.add(subtopic); } topicAssignments.add(topics); } } public void inference() throws IOException { System.out.println("Running Gibbs sampling inference: "); for (int iter = 1; iter <= numInitIterations; iter++) { System.out.println("\tInitial sampling iteration: " + (iter)); sampleSingleInitialIteration(); } for (int iter = 1; iter <= numIterations; iter++) { System.out.println("\tLFDMM sampling iteration: " + (iter)); optimizeTopicVectors(); sampleSingleIteration(); if ((savestep > 0) && (iter % savestep == 0) && (iter < numIterations)) { System.out.println("\t\tSaving the output from the " + iter + "^{th} sample"); expName = orgExpName + "-" + iter; write(); } } expName = orgExpName; writeParameters(); System.out.println("Writing output from the last sample ..."); write(); System.out.println("Sampling completed!"); } public void optimizeTopicVectors() { System.out.println("\t\tEstimating topic vectors ..."); sumExpValues = new double[numTopics]; dotProductValues = new double[numTopics][vocabularySize]; expDotProductValues = new double[numTopics][vocabularySize]; Parallel.loop(numTopics, new Parallel.LoopInt() { @Override public void compute(int topic) { int rate = 1; boolean check = true; while (check) { double l2Value = l2Regularizer * rate; try { TopicVectorOptimizer optimizer = new TopicVectorOptimizer( topicVectors[topic], topicWordCountLF[topic], wordVectors, l2Value); Optimizer gd = new LBFGS(optimizer, tolerance); gd.optimize(600); optimizer.getParameters(topicVectors[topic]); sumExpValues[topic] = optimizer .computePartitionFunction(dotProductValues[topic], expDotProductValues[topic]); check = false; if (sumExpValues[topic] == 0 || Double.isInfinite(sumExpValues[topic])) { double max = -1000000000.0; for (int index = 0; index < vocabularySize; index++) { if (dotProductValues[topic][index] > max) max = dotProductValues[topic][index]; } for (int index = 0; index < vocabularySize; index++) { expDotProductValues[topic][index] = Math .exp(dotProductValues[topic][index] - max); sumExpValues[topic] += expDotProductValues[topic][index]; } } } catch (InvalidOptimizableException e) { e.printStackTrace(); check = true; } rate = rate * 10; } } }); } public void sampleSingleIteration() { for (int dIndex = 0; dIndex < numDocuments; dIndex++) { List<Integer> document = corpus.get(dIndex); int docSize = document.size(); int topic = topicAssignments.get(dIndex).get(0) % numTopics; docTopicCount[topic] = docTopicCount[topic] - 1; for (int wIndex = 0; wIndex < docSize; wIndex++) { int word = document.get(wIndex);// wordId int subtopic = topicAssignments.get(dIndex).get(wIndex); if (subtopic == topic) { topicWordCountLF[topic][word] -= 1; sumTopicWordCountLF[topic] -= 1; } else { topicWordCountDMM[topic][word] -= 1; sumTopicWordCountDMM[topic] -= 1; } } // Sample a topic for (int tIndex = 0; tIndex < numTopics; tIndex++) { multiPros[tIndex] = (docTopicCount[tIndex] + alpha); for (int wIndex = 0; wIndex < docSize; wIndex++) { int word = document.get(wIndex); multiPros[tIndex] *= (lambda * expDotProductValues[tIndex][word] / sumExpValues[tIndex] + (1 - lambda) * (topicWordCountDMM[tIndex][word] + beta) / (sumTopicWordCountDMM[tIndex] + betaSum)); } } topic = FuncUtils.nextDiscrete(multiPros); docTopicCount[topic] += 1; for (int wIndex = 0; wIndex < docSize; wIndex++) { int word = document.get(wIndex); int subtopic = topic; if (lambda * expDotProductValues[topic][word] / sumExpValues[topic] > (1 - lambda) * (topicWordCountDMM[topic][word] + beta) / (sumTopicWordCountDMM[topic] + betaSum)) { topicWordCountLF[topic][word] += 1; sumTopicWordCountLF[topic] += 1; } else { topicWordCountDMM[topic][word] += 1; sumTopicWordCountDMM[topic] += 1; subtopic += numTopics; } // Update topic assignments topicAssignments.get(dIndex).set(wIndex, subtopic); } } } public void sampleSingleInitialIteration() { for (int dIndex = 0; dIndex < numDocuments; dIndex++) { List<Integer> document = corpus.get(dIndex); int docSize = document.size(); int topic = topicAssignments.get(dIndex).get(0) % numTopics; docTopicCount[topic] = docTopicCount[topic] - 1; for (int wIndex = 0; wIndex < docSize; wIndex++) { int word = document.get(wIndex); int subtopic = topicAssignments.get(dIndex).get(wIndex); if (topic == subtopic) { topicWordCountLF[topic][word] -= 1; sumTopicWordCountLF[topic] -= 1; } else { topicWordCountDMM[topic][word] -= 1; sumTopicWordCountDMM[topic] -= 1; } } // Sample a topic for (int tIndex = 0; tIndex < numTopics; tIndex++) { multiPros[tIndex] = (docTopicCount[tIndex] + alpha); for (int wIndex = 0; wIndex < docSize; wIndex++) { int word = document.get(wIndex); multiPros[tIndex] *= (lambda * (topicWordCountLF[tIndex][word] + beta) / (sumTopicWordCountLF[tIndex] + betaSum) + (1 - lambda) * (topicWordCountDMM[tIndex][word] + beta) / (sumTopicWordCountDMM[tIndex] + betaSum)); } } topic = FuncUtils.nextDiscrete(multiPros); docTopicCount[topic] += 1; for (int wIndex = 0; wIndex < docSize; wIndex++) { int word = document.get(wIndex);// wordID int subtopic = topic; if (lambda * (topicWordCountLF[topic][word] + beta) / (sumTopicWordCountLF[topic] + betaSum) > (1 - lambda) * (topicWordCountDMM[topic][word] + beta) / (sumTopicWordCountDMM[topic] + betaSum)) { topicWordCountLF[topic][word] += 1; sumTopicWordCountLF[topic] += 1; } else { topicWordCountDMM[topic][word] += 1; sumTopicWordCountDMM[topic] += 1; subtopic += numTopics; } // Update topic assignments topicAssignments.get(dIndex).set(wIndex, subtopic); } } } public void writeParameters() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(folderPath + expName + ".paras")); writer.write("-model" + "\t" + "LFDMM"); writer.write("\n-corpus" + "\t" + corpusPath); writer.write("\n-vectors" + "\t" + vectorFilePath); writer.write("\n-ntopics" + "\t" + numTopics); writer.write("\n-alpha" + "\t" + alpha); writer.write("\n-beta" + "\t" + beta); writer.write("\n-lambda" + "\t" + lambda); writer.write("\n-initers" + "\t" + numInitIterations); writer.write("\n-niters" + "\t" + numIterations); writer.write("\n-twords" + "\t" + topWords); writer.write("\n-name" + "\t" + expName); if (savestep > 0) writer.write("\n-sstep" + "\t" + savestep); writer.close(); } public void writeDictionary() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(folderPath + expName + ".vocabulary")); for (String word : word2IdVocabulary.keySet()) { writer.write(word + " " + word2IdVocabulary.get(word) + "\n"); } writer.close(); } public void writeIDbasedCorpus() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(folderPath + expName + ".IDcorpus")); for (int dIndex = 0; dIndex < numDocuments; dIndex++) { int docSize = corpus.get(dIndex).size(); for (int wIndex = 0; wIndex < docSize; wIndex++) { writer.write(corpus.get(dIndex).get(wIndex) + " "); } writer.write("\n"); } writer.close(); } public void writeTopicAssignments() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(folderPath + expName + ".topicAssignments")); for (int dIndex = 0; dIndex < numDocuments; dIndex++) { int docSize = corpus.get(dIndex).size(); for (int wIndex = 0; wIndex < docSize; wIndex++) { writer.write(topicAssignments.get(dIndex).get(wIndex) + " "); } writer.write("\n"); } writer.close(); } public void writeTopicVectors() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(folderPath + expName + ".topicVectors")); for (int i = 0; i < numTopics; i++) { for (int j = 0; j < vectorSize; j++) writer.write(topicVectors[i][j] + " "); writer.write("\n"); } writer.close(); } public void writeTopTopicalWords() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(folderPath + expName + ".topWords")); for (int tIndex = 0; tIndex < numTopics; tIndex++) { writer.write("Topic" + new Integer(tIndex) + ":"); Map<Integer, Double> topicWordProbs = new TreeMap<Integer, Double>(); for (int wIndex = 0; wIndex < vocabularySize; wIndex++) { double pro = lambda * expDotProductValues[tIndex][wIndex] / sumExpValues[tIndex] + (1 - lambda) * (topicWordCountDMM[tIndex][wIndex] + beta) / (sumTopicWordCountDMM[tIndex] + betaSum); topicWordProbs.put(wIndex, pro); } topicWordProbs = FuncUtils.sortByValueDescending(topicWordProbs); Set<Integer> mostLikelyWords = topicWordProbs.keySet(); int count = 0; for (Integer index : mostLikelyWords) { if (count < topWords) { writer.write(" " + id2WordVocabulary.get(index)); count += 1; } else { writer.write("\n\n"); break; } } } writer.close(); } public void writeTopicWordPros() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(folderPath + expName + ".phi")); for (int t = 0; t < numTopics; t++) { for (int w = 0; w < vocabularySize; w++) { double pro = lambda * expDotProductValues[t][w] / sumExpValues[t] + (1 - lambda) * (topicWordCountDMM[t][w] + beta) / (sumTopicWordCountDMM[t] + betaSum); writer.write(pro + " "); } writer.write("\n"); } writer.close(); } public void writeDocTopicPros() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(folderPath + expName + ".theta")); for (int i = 0; i < numDocuments; i++) { int docSize = corpus.get(i).size(); double sum = 0.0; for (int tIndex = 0; tIndex < numTopics; tIndex++) { multiPros[tIndex] = (docTopicCount[tIndex] + alpha); for (int wIndex = 0; wIndex < docSize; wIndex++) { int word = corpus.get(i).get(wIndex); multiPros[tIndex] *= (lambda * expDotProductValues[tIndex][word] / sumExpValues[tIndex] + (1 - lambda) * (topicWordCountDMM[tIndex][word] + beta) / (sumTopicWordCountDMM[tIndex] + betaSum)); } sum += multiPros[tIndex]; } for (int tIndex = 0; tIndex < numTopics; tIndex++) { writer.write((multiPros[tIndex] / sum) + " "); } writer.write("\n"); } writer.close(); } public void write() throws IOException { writeTopTopicalWords(); writeDocTopicPros(); writeTopicAssignments(); writeTopicWordPros(); } public static void main(String args[]) throws Exception { LFDMM_Inf lfdmm = new LFDMM_Inf("test/testLFDMM.paras", "test/corpus_test.txt", 2000, 200, 20, "testLFDMMinf", 0); lfdmm.inference(); } }
datquocnguyen/LFTM
src/models/LFDMM_Inf.java
213,997
/* An abstraction for Unit constraints. Copyright (c) 2003-2014 The Regents of the University of California. All rights reserved. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. PT_COPYRIGHT_VERSION_3 COPYRIGHTENDKEY */ package ptolemy.moml.unit; import ptolemy.kernel.util.NamedObj; /////////////////////////////////////////////////////////////////// //// UnitConstraint /** @author Rowland R Johnson @version $Id$ @since Ptolemy II 8.0 @Pt.ProposedRating Red (rowland) @Pt.AcceptedRating Red (rowland) */ public abstract class UnitConstraint { /** * @param string */ public UnitConstraint(String string) { // TODO Auto-generated constructor stub } /** * @param lhs * @param operator * @param rhs */ public UnitConstraint(UnitExpr lhs, String operator, UnitExpr rhs) { _lhs = lhs; _operator = operator; _rhs = rhs; } /////////////////////////////////////////////////////////////////// //// public methods //// /* (non-Javadoc) * @see ptolemy.moml.unit.UnitPresentation#commonDesc() */ public String descriptiveForm() { return _lhs.descriptiveForm() + _operator + _rhs.descriptiveForm(); } /** Get the left hand side. * @return The left hand side. */ public UnitExpr getLhs() { return _lhs; } /** * @return The operator. */ public String getOperator() { return _operator; } /** Get the right hand side. * @return The right hand side. */ public UnitExpr getRhs() { return _rhs; } /** Get the source of this equation. * @return The source of this equation. */ public NamedObj getSource() { return _source; } public void setLhs(UnitExpr expr) { _lhs = expr; } public void setRhs(UnitExpr expr) { _rhs = expr; } public void setSource(NamedObj source) { _source = source; } @Override public String toString() { return _lhs.toString() + _operator + _rhs.toString(); } /////////////////////////////////////////////////////////////////// //// private variables //// UnitExpr _lhs; /////////////////////////////////////////////////////////////////// //// private variables //// UnitExpr _rhs; String _operator; NamedObj _source = null; }
erwindl0/ptII
ptolemy/moml/unit/UnitConstraint.java
213,998
// Copyright 2002-2007, FreeHEP. package org.freehep.xml.util; import java.awt.Color; import java.io.IOException; import java.io.Writer; import java.util.Enumeration; import java.util.Hashtable; import java.util.Stack; import org.freehep.util.io.IndentPrintWriter; /** * A class that makes it easy to write XML documents. * * @author Tony Johnson * @author Mark Donszelmann * @version $Id: XMLWriter.java,v 1.3 2008-05-04 12:20:34 murkle Exp $ */ public class XMLWriter implements XMLTagWriter { public XMLWriter(Writer w, String indentString, String defaultNameSpace) { writer = new IndentPrintWriter(w); writer.setIndentString(indentString); this.defaultNameSpace = defaultNameSpace; } public XMLWriter(Writer w, String indentString) { this(w, indentString, ""); } public XMLWriter(Writer w) { this(w, " "); // By popular demand of Babar } /** * closes the writer */ @Override public void close() throws IOException { closeDoc(); writer.close(); } /** * Opens the document with an xml header */ @Override public void openDoc() { openDoc("1.0", "", false); } /** * Opens the document with an xml header */ @Override public void openDoc(String version, String encoding, boolean standalone) { String indentString = writer.getIndentString(); writer.setIndentString(indentString); closed = false; if (!XMLCharacterProperties.validVersionNum(version)) { throw new RuntimeException("Invalid version number: " + version); } writer.print("<?xml version=\""); writer.print(version); writer.print("\" "); if ((encoding != null) && (!encoding.equals(""))) { if (!XMLCharacterProperties.validEncName(encoding)) { throw new RuntimeException( "Invalid encoding name: " + encoding); } writer.print("encoding=\""); writer.print(encoding); writer.print("\" "); } if (standalone) { writer.print("standalone=\"yes\" "); } writer.println("?>"); writer.setIndentString(indentString); } /** * Writes a reference to a DTD */ @Override public void referToDTD(String name, String pid, String ref) { if (dtdName != null) { throw new RuntimeException("ReferToDTD cannot be called twice"); } dtdName = name; writer.println("<!DOCTYPE " + name + " PUBLIC \"" + pid + "\" \"" + ref + "\">"); } /** * Writes a reference to a DTD */ @Override public void referToDTD(String name, String system) { if (dtdName != null) { throw new RuntimeException("ReferToDTD cannot be called twice"); } dtdName = name; writer.println("<!DOCTYPE " + name + " SYSTEM \"" + system + "\">"); } /** * Closes the document, and checks if you closed all the tags */ @Override public void closeDoc() { if (!closed) { if (!openTags.isEmpty()) { StringBuffer sb = new StringBuffer( "Not all tags were closed before closing XML document:\n"); while (!openTags.isEmpty()) { sb.append(" </"); sb.append((String) openTags.pop()); sb.append(">\n"); } throw new RuntimeException(sb.toString()); } closed = true; } writer.flush(); } /** * Print a comment */ @Override public void printComment(String comment) { if (comment.indexOf("--") >= 0) { throw new RuntimeException("'--' sequence not allowed in comment"); } writer.print("<!--"); writer.print(normalizeText(comment)); writer.println("-->"); } /** * Prints character data, while escaping &lt; and &gt; */ @Override public void print(String text) { writer.print(normalizeText(text)); } /** * Prints character data, while escaping &lt; and &gt; */ public void println(String text) { print(text); writer.println(); } /** * Prints a new XML tag and increases the identation level */ @Override public void openTag(String namespace, String name) { if (namespace.equals(defaultNameSpace)) { openTag(name); } else { openTag(namespace + ":" + name); } } /** * Prints a new XML tag and increases the identation level */ @Override public void openTag(String name) { checkNameValid(name); if (openTags.isEmpty() && dtdName != null && !dtdName.equals(name)) { throw new RuntimeException("First tag: '" + name + "' not equal to DTD id: '" + dtdName + "'"); } writer.print("<" + name); printAttributes(name.length()); writer.println(">"); writer.indent(); openTags.push(name); } /** * Closes the current XML tag and decreases the indentation level */ @Override public void closeTag() { if (openTags.isEmpty()) { writer.close(); throw new RuntimeException("No open tags"); } Object name = openTags.pop(); writer.outdent(); writer.print("</"); writer.print(name); writer.println(">"); } /** * Prints an empty XML tag. */ @Override public void printTag(String namespace, String name) { if (namespace.equals(defaultNameSpace)) { printTag(name); } else { printTag(namespace + ":" + name); } } /** * Prints an empty XML tag. */ @Override public void printTag(String name) { checkNameValid(name); writer.print("<" + name); printAttributes(name.length()); writer.println("/>"); } /** * Sets an attribute which will be included in the next tag printed by * openTag or printTag */ @Override public void setAttribute(String name, String value) { if ((name != null) && (value != null)) { attributes.put(name, value); } } @Override public void setAttribute(String namespace, String name, String value) { if ((namespace != null) && (name != null)) { attributes.put(namespace + ":" + name, value); } } @Override public void setAttribute(String name, byte value) { setAttribute(name, String.valueOf(value)); } @Override public void setAttribute(String name, char value) { setAttribute(name, String.valueOf(value)); } @Override public void setAttribute(String name, long value) { setAttribute(name, String.valueOf(value)); } @Override public void setAttribute(String name, int value) { setAttribute(name, String.valueOf(value)); } @Override public void setAttribute(String name, short value) { setAttribute(name, String.valueOf(value)); } @Override public void setAttribute(String name, boolean value) { setAttribute(name, String.valueOf(value)); } @Override public void setAttribute(String name, float value) { setAttribute(name, String.valueOf(value)); } @Override public void setAttribute(String name, double value) { setAttribute(name, String.valueOf(value)); } @Override public void setAttribute(String name, Color value) { setAttribute(name, String.valueOf(value)); } @Override public void setAttribute(String ns, String name, byte value) { setAttribute(ns + ":" + name, String.valueOf(value)); } @Override public void setAttribute(String ns, String name, char value) { setAttribute(ns + ":" + name, String.valueOf(value)); } @Override public void setAttribute(String ns, String name, long value) { setAttribute(ns + ":" + name, String.valueOf(value)); } @Override public void setAttribute(String ns, String name, int value) { setAttribute(ns + ":" + name, String.valueOf(value)); } @Override public void setAttribute(String ns, String name, short value) { setAttribute(ns + ":" + name, String.valueOf(value)); } @Override public void setAttribute(String ns, String name, boolean value) { setAttribute(ns + ":" + name, String.valueOf(value)); } @Override public void setAttribute(String ns, String name, float value) { setAttribute(ns + ":" + name, String.valueOf(value)); } @Override public void setAttribute(String ns, String name, double value) { setAttribute(ns + ":" + name, String.valueOf(value)); } @Override public void setAttribute(String ns, String name, Color value) { setAttribute(ns + ":" + name, String.valueOf(value)); } protected void printAttributes(int tagLength) { int width = tagLength + 1; boolean extraIndent = false; Enumeration e = attributes.keys(); while (e.hasMoreElements()) { String key = e.nextElement().toString(); checkNameValid(key); String value = normalize(attributes.get(key).toString()); int length = key.length() + value.length() + 3; if (width > 0 && width + length + 2 * writer.getIndent() > 60) { width = 0; writer.println(); if (!extraIndent) { writer.indent(); extraIndent = true; } } else { width += length; writer.print(' '); } writer.print(key); writer.print("=\""); writer.print(value); writer.print("\""); } attributes.clear(); if (extraIndent) { writer.outdent(); } } // /** // * Prints a DOM node, recursively. // * No support for a document node // */ // public void print(Node node) // { // if ( node == null ) return; // // int type = node.getNodeType(); // switch ( type ) { // // print document // case Node.DOCUMENT_NODE: // throw new RuntimeException("No support for printing nodes of type // Document"); // // // print element with attributes // case Node.ELEMENT_NODE: // NamedNodeMap attributes = node.getAttributes(); // for ( int i = 0; i < attributes.getLength(); i++ ) { // Node attr = attributes.item(i); // setAttribute(attr.getNodeName(), attr.getNodeValue()); // } // NodeList children = node.getChildNodes(); // if ( children == null ) { // printTag(node.getNodeName()); // } else { // openTag(node.getNodeName()); // int len = children.getLength(); // for ( int i = 0; i < len; i++ ) { // print(children.item(i)); // } // closeTag(); // } // break; // // // handle entity reference nodes // case Node.ENTITY_REFERENCE_NODE: // writer.print('&'); // writer.print(node.getNodeName()); // writer.print(';'); // break; // // // print cdata sections // case Node.CDATA_SECTION_NODE: // writer.print("<![CDATA["); // writer.print(node.getNodeValue()); // writer.print("]]>"); // break; // // // print text // case Node.TEXT_NODE: // print(node.getNodeValue()); // break; // // // print processing instruction // case Node.PROCESSING_INSTRUCTION_NODE: // writer.print("<?"); // writer.print(node.getNodeName()); // String data = node.getNodeValue(); // if ( data != null && data.length() > 0 ) { // writer.print(' '); // writer.print(data); // } // writer.print("?>"); // break; // } // } // print(Node) /** Normalizes the given string for an Attribute value */ public static String normalize(String s) { StringBuffer str = new StringBuffer(); int len = (s != null) ? s.length() : 0; for (int i = 0; i < len; i++) { char ch = s.charAt(i); switch (ch) { case '<': { str.append("&lt;"); break; } case '>': { str.append("&gt;"); break; } case '&': { str.append("&amp;"); break; } case '"': { str.append("&quot;"); break; } case '\r': case '\n': { str.append("&#"); str.append(Integer.toString(ch)); str.append(';'); break; } default: { if (ch > 0x00FF) { String hex = "0000" + Integer.toHexString(ch); str.append("&#x"); str.append(hex.substring(hex.length() - 4)); str.append(';'); } else { str.append(ch); } } } } return str.toString(); } // normalize(String):String /** Normalizes the given string for Text */ public static String normalizeText(String s) { StringBuffer str = new StringBuffer(); int len = (s != null) ? s.length() : 0; for (int i = 0; i < len; i++) { char ch = s.charAt(i); switch (ch) { case '<': { str.append("&lt;"); break; } case '>': { str.append("&gt;"); break; } case '&': { str.append("&amp;"); break; } default: { if (ch > 0x007f) { String hex = "0000" + Integer.toHexString(ch); str.append("&#x"); str.append(hex.substring(hex.length() - 4)); str.append(';'); } else { str.append(ch); } } } } return str.toString(); } protected void checkNameValid(String s) { if (!XMLCharacterProperties.validName(s)) { throw new RuntimeException("Invalid name: " + s); } } protected boolean closed = true; private String dtdName = null; private Hashtable attributes = new Hashtable(); private Stack openTags = new Stack(); protected IndentPrintWriter writer; protected String defaultNameSpace; }
mstfelg/geosquared
desktop/src/main/java/org/freehep/xml/util/XMLWriter.java
213,999
package com.etsy.statsd.profiler; import com.etsy.statsd.profiler.reporter.Reporter; import com.etsy.statsd.profiler.server.ProfilerServer; import com.etsy.statsd.profiler.worker.ProfilerShutdownHookWorker; import com.etsy.statsd.profiler.worker.ProfilerThreadFactory; import com.etsy.statsd.profiler.worker.ProfilerWorkerThread; import com.google.common.util.concurrent.MoreExecutors; import java.lang.instrument.Instrumentation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.atomic.AtomicReference; /** * javaagent profiler using StatsD as a backend * * @author Andrew Johnson */ public final class Agent { public static final int EXECUTOR_DELAY = 0; static AtomicReference<Boolean> isRunning = new AtomicReference<>(true); static LinkedList<String> errors = new LinkedList<>(); private Agent() { } public static void agentmain(final String args, final Instrumentation instrumentation) { premain(args, instrumentation); } /** * Start the profiler * * @param args Profiler arguments * @param instrumentation Instrumentation agent */ public static void premain(final String args, final Instrumentation instrumentation) { Arguments arguments = Arguments.parseArgs(args); Reporter reporter = instantiate(arguments.reporter, Reporter.CONSTRUCTOR_PARAM_TYPES, arguments); Collection<Profiler> profilers = new ArrayList<>(); for (Class<? extends Profiler> profiler : arguments.profilers) { profilers.add(instantiate(profiler, Profiler.CONSTRUCTOR_PARAM_TYPES, reporter, arguments)); } scheduleProfilers(profilers, arguments); registerShutdownHook(profilers); } /** * Schedule profilers with a SchedulerExecutorService * * @param profilers Collection of profilers to schedule * @param arguments */ private static void scheduleProfilers(Collection<Profiler> profilers, Arguments arguments) { // We need to convert to an ExitingScheduledExecutorService so the JVM shuts down // when the main thread finishes ScheduledExecutorService scheduledExecutorService = MoreExecutors.getExitingScheduledExecutorService( (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(profilers.size(), new ProfilerThreadFactory())); Map<String, ScheduledFuture<?>> runningProfilers = new HashMap<>(profilers.size()); Map<String, Profiler> activeProfilers = new HashMap<>(profilers.size()); for (Profiler profiler : profilers) { activeProfilers.put(profiler.getClass().getSimpleName(), profiler); ProfilerWorkerThread worker = new ProfilerWorkerThread(profiler, errors); ScheduledFuture future = scheduledExecutorService.scheduleAtFixedRate(worker, EXECUTOR_DELAY, profiler.getPeriod(), profiler.getTimeUnit()); runningProfilers.put(profiler.getClass().getSimpleName(), future); } if (arguments.httpServerEnabled) { ProfilerServer.startServer(runningProfilers, activeProfilers, arguments.httpPort, isRunning, errors); } } /** * Register a shutdown hook to flush profiler data to StatsD * * @param profilers The profilers to flush at shutdown */ private static void registerShutdownHook(Collection<Profiler> profilers) { Thread shutdownHook = new Thread(new ProfilerShutdownHookWorker(profilers, isRunning)); Runtime.getRuntime().addShutdownHook(shutdownHook); } /** * Uniformed handling of initialization exception * * @param clazz The class that could not be instantiated * @param cause The underlying exception */ private static void handleInitializationException(final Class<?> clazz, final Exception cause) { throw new RuntimeException("Unable to instantiate " + clazz.getSimpleName(), cause); } /** * Instantiate an object * * @param clazz A Class representing the type of object to instantiate * @param parameterTypes The parameter types for the constructor * @param initArgs The values to pass to the constructor * @param <T> The type of the object to instantiate * @return A new instance of type T */ private static <T> T instantiate(final Class<T> clazz, Class<?>[] parameterTypes, Object... initArgs) { try { Constructor<T> constructor = clazz.getConstructor(parameterTypes); return constructor.newInstance(initArgs); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { handleInitializationException(clazz, e); } return null; } }
etsy/statsd-jvm-profiler
src/main/java/com/etsy/statsd/profiler/Agent.java
214,000
/** * The MIT License * ------------------------------------------------------------- * Copyright (c) 2008, Rob Ellis, Brock Whitten, Brian Leroux, Joe Bowser, Dave Johnson, Nitobi * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.nitobi.phonegap.api.impl; import javax.microedition.location.Location; import javax.microedition.location.LocationException; import javax.microedition.location.LocationListener; import javax.microedition.location.LocationProvider; import net.rim.blackberry.api.invoke.Invoke; import net.rim.blackberry.api.invoke.MapsArguments; import com.nitobi.phonegap.PhoneGap; import com.nitobi.phonegap.api.Command; import com.nitobi.phonegap.model.Position; /** * Wraps all GPS functions. * * @author Jose Noheda * */ public class GeoLocationCommand implements Command { private static final int MAP_COMMAND = 0; private static final int STOP_COMMAND = 1; private static final int START_COMMAND = 2; private static final int CAPTURE_INTERVAL = 5; private static final String CODE = "PhoneGap=location"; private static final String GEO_NS = "navigator.geolocation."; private static final String GEO_STOP = GEO_NS + "started = false;" + GEO_NS + "lastPosition = null;"; private static final String GEO_START = GEO_NS + "started = true;"; private static final String GEO_SET_LOCATION = GEO_NS + "setLocation("; private static final String GEO_SET_ERROR = GEO_NS + "setError("; private static final String FUNC_SUF = ");"; private static final String ERROR_UNAVAILABLE = "'GPS unavailable on this device.'"; private static final String ERROR_OUTOFSERVICE = "'GPS is out of service on this device.'"; private PhoneGap berryGap; private Position position; private boolean availableGPS = true; private LocationProvider locationProvider; public GeoLocationCommand(PhoneGap phoneGap) { this.berryGap = phoneGap; try { locationProvider = LocationProvider.getInstance(null); // Passing null as the parameter is equal to passing a Criteria that has all fields set to the default values, // i.e. the least restrictive set of criteria. } catch (LocationException e) { availableGPS = false; locationProvider = null; } } /** * Determines whether the specified instruction is accepted by the command. * @param instruction The string instruction passed from JavaScript via cookie. * @return true if the Command accepts the instruction, false otherwise. */ public boolean accept(String instruction) { return instruction != null && instruction.startsWith(CODE); } /** * Deletes the last valid obtained position. */ public void clearPosition() { position = null; } /** * Executes the following sub-commands: * START: Initializes the internal GPS module * STOP: Stops GPS module (saving battery life) * CHECK: Reads latest position available * MAP: Invokes the internal MAP application */ public String execute(String instruction) { if (!availableGPS) return setError(ERROR_UNAVAILABLE); switch (getCommand(instruction)) { case MAP_COMMAND: if (position != null) Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments(MapsArguments.ARG_LOCATION_DOCUMENT, getLocationDocument())); break; case STOP_COMMAND: clearPosition(); locationProvider.setLocationListener(null, 0, 0, 0); return GEO_STOP; case START_COMMAND: locationProvider.setLocationListener(new LocationListenerImpl(this), CAPTURE_INTERVAL, 1, 1); return GEO_START; } return null; } /** * Parses the specified instruction and the parameters and determines what type of functional call is being made. * @param instruction The string instruction passed from JavaScript via cookie. * @return Integer representing action type. */ private int getCommand(String instruction) { String command = instruction.substring(instruction.lastIndexOf('/') + 1); if ("map".equals(command)) return MAP_COMMAND; if ("stop".equals(command)) return STOP_COMMAND; if ("start".equals(command)) return START_COMMAND; return -1; } private void updateLocation(double lat, double lng, float altitude, float accuracy, float alt_accuracy, float heading, float speed, long time) { position = new Position(); position.setLatitude(lat); position.setLongitude(lng); position.setAltitude(altitude); position.setAccuracy(accuracy); position.setAltitudeAccuracy(alt_accuracy); position.setHeading(heading); position.setVelocity(speed); position.setTimestamp(time); berryGap.pendingResponses.addElement(GEO_SET_LOCATION + position.toJavascript() + FUNC_SUF); } private String setError(String error) { return GEO_SET_ERROR + error + FUNC_SUF; } private String getLocationDocument() { StringBuffer location = new StringBuffer("<location-document><location x=\""); location.append(position.getLatitude()).append("\" y=\""); location.append(position.getLongitude()).append("\" label=\"Here\" description=\"Unavailable\""); location.append("/></location-document>"); return location.toString(); } /** * Implementation of the LocationListener interface */ private class LocationListenerImpl implements LocationListener { private GeoLocationCommand command; public LocationListenerImpl(GeoLocationCommand command) { this.command = command; } public void locationUpdated(LocationProvider provider, Location location) { if (location.isValid()) { double latitude = location.getQualifiedCoordinates().getLatitude(); double longitude = location.getQualifiedCoordinates().getLongitude(); float altitude = location.getQualifiedCoordinates().getAltitude(); float accuracy = location.getQualifiedCoordinates().getHorizontalAccuracy(); float alt_accuracy = location.getQualifiedCoordinates().getVerticalAccuracy(); float heading = location.getCourse(); float speed = location.getSpeed(); long timestamp = location.getTimestamp(); command.updateLocation(latitude, longitude, altitude, accuracy, alt_accuracy, heading, speed, timestamp); } else command.clearPosition(); } public void providerStateChanged(LocationProvider provider, int newState) { switch (newState) { case LocationProvider.AVAILABLE: break; case LocationProvider.OUT_OF_SERVICE: command.setError(ERROR_OUTOFSERVICE); break; case LocationProvider.TEMPORARILY_UNAVAILABLE: break; } } } }
claymodel/phonegap
blackberry/framework/src/com/nitobi/phonegap/api/impl/GeoLocationCommand.java
214,001
/******************************************************************************* * Copyright (c) 1997, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jsp; import java.io.PrintWriter; import java.io.StringWriter; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * @author Scott Johnson * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class BasicLogFormatter extends Formatter { private String lineSeparator = (String) java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() {public Object run() {return System.getProperty("line.separator");}}); /* (non-Javadoc) * @see java.util.logging.Formatter#format(java.util.logging.LogRecord) */ public String format(LogRecord record) { StringBuffer sb = new StringBuffer(); String message = formatMessage(record); sb.append(message); sb.append(lineSeparator); if (record.getThrown() != null) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); sb.append(sw.toString()); } catch (Exception ex) { if (record.getThrown().getCause() != null){ sb.append(record.getThrown().getCause().getLocalizedMessage()); }else{ sb.append(record.getThrown().getLocalizedMessage()); } } } return sb.toString(); } }
tjwatson/open-liberty
dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/BasicLogFormatter.java
214,002
package it.snipsnap.slyce_messaging_example; import android.net.Uri; import android.os.Bundle; import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import it.slyce.messaging.SlyceMessagingFragment; import it.slyce.messaging.listeners.LoadMoreMessagesListener; import it.slyce.messaging.listeners.OnOptionSelectedListener; import it.slyce.messaging.listeners.UserSendsMessageListener; import it.slyce.messaging.message.GeneralOptionsMessage; import it.slyce.messaging.message.MediaMessage; import it.slyce.messaging.message.Message; import it.slyce.messaging.message.MessageSource; import it.slyce.messaging.message.TextMessage; public class MainActivity extends AppCompatActivity { private static String[] latin = { "Vestibulum dignissim enim a mauris malesuada fermentum. Vivamus tristique consequat turpis, pellentesque.", "Quisque nulla leo, venenatis ut augue nec, dictum gravida nibh. Donec augue nisi, volutpat nec libero.", "Cras varius risus a magna egestas.", "Mauris tristique est eget massa mattis iaculis. Aenean sed purus tempus, vestibulum ante eget, vulputate mi. Pellentesque hendrerit luctus tempus. Cras feugiat orci.", "Morbi ullamcorper, sapien mattis viverra facilisis, nisi urna sagittis nisi, at luctus lectus elit.", "Phasellus porttitor fermentum neque. In semper, libero id mollis.", "Praesent fermentum hendrerit leo, ac rutrum ipsum vestibulum at. Curabitur pellentesque augue.", "Mauris finibus mi commodo molestie placerat. Curabitur aliquam metus vitae erat vehicula ultricies. Sed non quam nunc.", "Praesent vel velit at turpis vestibulum eleifend ac vehicula leo. Nunc lacinia tellus eget ipsum consequat fermentum. Nam purus erat, mollis sed ullamcorper nec, efficitur.", "Suspendisse volutpat enim eros, et." }; private static String[] urls = { "http://en.l4c.me/fullsize/googleplex-mountain-view-california-1242979177.jpg", "http://entropymag.org/wp-content/uploads/2014/10/outer-space-wallpaper-pictures.jpg", "http://www.bolwell.com/wp-content/uploads/2013/09/bolwell-metal-fabrication-raw-material.jpg", "http://www.bytscomputers.com/wp-content/uploads/2013/12/pc.jpg", "https://content.edmc.edu/assets/modules/ContentWebParts/AI/Locations/New-York-City/startpage-masthead-slide.jpg" }; private volatile static int n = 0; private static Message getRandomMessage() { n++; Message message; if (Math.random() < 1.1) { TextMessage textMessage = new TextMessage(); textMessage.setText(n + ""); // + ": " + latin[(int) (Math.random() * 10)]); message = textMessage; } else { MediaMessage mediaMessage = new MediaMessage(); mediaMessage.setUrl(urls[(int)(Math.random() * 5)]); message = mediaMessage; } message.setDate(new Date().getTime()); if (Math.random() > 0.5) { message.setAvatarUrl("https://lh3.googleusercontent.com/-Y86IN-vEObo/AAAAAAAAAAI/AAAAAAAKyAM/6bec6LqLXXA/s0-c-k-no-ns/photo.jpg"); message.setUserId("LP"); message.setSource(MessageSource.EXTERNAL_USER); } else { message.setAvatarUrl("https://scontent-lga3-1.xx.fbcdn.net/v/t1.0-9/10989174_799389040149643_722795835011402620_n.jpg?oh=bff552835c414974cc446043ac3c70ca&oe=580717A5"); message.setUserId("MP"); message.setSource(MessageSource.LOCAL_USER); } return message; } SlyceMessagingFragment slyceMessagingFragment; private boolean hasLoadedMore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(it.snipsnap.slyce_messaging_example.R.layout.activity_main); hasLoadedMore = false; slyceMessagingFragment = (SlyceMessagingFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_for_slyce_messaging); slyceMessagingFragment.setDefaultAvatarUrl("https://scontent-lga3-1.xx.fbcdn.net/v/t1.0-9/10989174_799389040149643_722795835011402620_n.jpg?oh=bff552835c414974cc446043ac3c70ca&oe=580717A5"); slyceMessagingFragment.setDefaultDisplayName("Matthew Page"); slyceMessagingFragment.setDefaultUserId("uhtnaeohnuoenhaeuonthhntouaetnheuontheuo"); slyceMessagingFragment.setOnSendMessageListener(new UserSendsMessageListener() { @Override public void onUserSendsTextMessage(String text) { Log.d("inf", "******************************** " + text); } @Override public void onUserSendsMediaMessage(Uri imageUri) { Log.d("inf", "******************************** " + imageUri); } }); slyceMessagingFragment.setLoadMoreMessagesListener(new LoadMoreMessagesListener() { @Override public List<Message> loadMoreMessages() { Log.d("info", "loadMoreMessages()"); if (!hasLoadedMore) { hasLoadedMore = true; ArrayList<Message> messages = new ArrayList<>(); GeneralOptionsMessage generalTextMessage = new GeneralOptionsMessage(); generalTextMessage.setTitle("Started group"); generalTextMessage.setFinalText("Accepted"); generalTextMessage.setOptions(new String[]{"Accept", "Reject"}); generalTextMessage.setOnOptionSelectedListener(new OnOptionSelectedListener() { @Override public String onOptionSelected(int optionSelected) { if (optionSelected == 0) { return "Accepted"; } else { return "Rejected"; } } }); messages.add(generalTextMessage); for (int i = 0; i < 50; i++) messages.add(getRandomMessage()); messages.add(generalTextMessage); Log.d("info", "loadMoreMessages() returns"); return messages; } else { slyceMessagingFragment.setMoreMessagesExist(false); return new ArrayList<>(); } } }); slyceMessagingFragment.setMoreMessagesExist(true); try { Thread.sleep(1000 * 3); } catch (InterruptedException e) { e.printStackTrace(); } ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1); scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { TextMessage textMessage = new TextMessage(); textMessage.setText("Another message..."); textMessage.setAvatarUrl("https://lh3.googleusercontent.com/-Y86IN-vEObo/AAAAAAAAAAI/AAAAAAAKyAM/6bec6LqLXXA/s0-c-k-no-ns/photo.jpg"); textMessage.setDisplayName("Gary Johnson"); textMessage.setUserId("LP"); textMessage.setDate(new Date().getTime()); textMessage.setSource(MessageSource.EXTERNAL_USER); slyceMessagingFragment.addNewMessage(textMessage); } }, 3, 3, TimeUnit.SECONDS); } }
RobertGolosynsky/SlyceMessaging
example/src/main/java/it/snipsnap/slyce_messaging_example/MainActivity.java
214,003
package chapter5.section1; import chapter1.section3.Queue; import chapter2.section1.InsertionSort; import edu.princeton.cs.algs4.StdOut; import java.util.StringJoiner; /** * Created by Rene Argento on 10/01/18. */ // Based on https://www.geeksforgeeks.org/bucket-sort-2/ @SuppressWarnings("unchecked") public class Exercise11_QueueSort { // O(N^2), but runs in O(N) if items are uniformly distributed in the buckets public class BucketSort { private int alphabetSize = 256; // Extended ASCII characters private Queue<String>[] buckets; public void bucketSort(String[] strings) { buckets = new Queue[alphabetSize + 1]; for (int bucket = 0; bucket < buckets.length; bucket++) { buckets[bucket] = new Queue(); } // 1- Put strings in bins for (int i = 0; i < strings.length; i++) { int leadingDigitIndex = strings[i].charAt(0); buckets[leadingDigitIndex].enqueue(strings[i]); } // 2- Sort the sublists for (int bucket = 0; bucket < buckets.length; bucket++) { if (!buckets[bucket].isEmpty()) { sortBucket(buckets[bucket]); } } // 3- Stitch together all the buckets int arrayIndex = 0; for (int r = 0; r <= alphabetSize; r++) { while (!buckets[r].isEmpty()) { String currentString = buckets[r].dequeue(); strings[arrayIndex++] = currentString; } } } private void sortBucket(Queue<String> bucket) { String[] strings = new String[bucket.size()]; int arrayIndex = 0; while (!bucket.isEmpty()) { strings[arrayIndex++] = bucket.dequeue(); } InsertionSort.insertionSort(strings); for (String string : strings) { bucket.enqueue(string); } } } public static void main(String[] args) { BucketSort bucketSort = new Exercise11_QueueSort().new BucketSort(); String[] array1 = {"Rene", "Argento", "Arg", "Alg", "Algorithms", "LSD", "MSD", "3WayStringQuickSort", "Dijkstra", "Floyd", "Warshall", "Johnson", "Sedgewick", "Wayne", "Bellman", "Ford", "BFS", "DFS"}; bucketSort.bucketSort(array1); StringJoiner sortedArray1 = new StringJoiner(" "); for (String string : array1) { sortedArray1.add(string); } StdOut.println("Sorted array 1"); StdOut.println(sortedArray1); StdOut.println("Expected: \n3WayStringQuickSort Alg Algorithms Arg Argento BFS Bellman DFS Dijkstra Floyd Ford " + "Johnson LSD MSD Rene Sedgewick Warshall Wayne\n"); String[] array2 = {"QuickSort", "MergeSort", "ShellSort", "InsertionSort", "BubbleSort", "SelectionSort"}; bucketSort.bucketSort(array2); StringJoiner sortedArray2 = new StringJoiner(" "); for (String string : array2) { sortedArray2.add(string); } StdOut.println("Sorted array 2"); StdOut.println(sortedArray2); StdOut.println("Expected: \nBubbleSort InsertionSort MergeSort QuickSort SelectionSort ShellSort"); } }
reneargento/algorithms-sedgewick-wayne
src/chapter5/section1/Exercise11_QueueSort.java
214,005
package zingg.client.util; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.IntStream; import java.util.stream.Stream; public class CliUtils { /* * leftJustifiedRows - If true, it will add "-" as a flag to format string to * make it left justified. Otherwise right justified. */ private static boolean leftJustifiedRows = false; private static int maxColumnWidth = 50; public static void formatIntoTable(List<String[]> table) { List<String[]> finalTable = prepareColumnTexts(table, maxColumnWidth); //Sritng[][] finalTable = prepareColumnTexts(table, maxColumnWidth); Map<Integer, Integer> columnLengths = calculateColumnsLength(finalTable); final StringBuilder formatString = buildFormatString(columnLengths); String line = buildDemarcationLine(columnLengths); /* * Print data table on screen */ System.out.print(line); //Arrays.stream(finalTable).limit(1).forEach(a -> System.out.printf(formatString.toString(), a)); table.stream().limit(1).forEach(a -> System.out.printf(formatString.toString(), a)); System.out.print(line); /* IntStream.iterate(1, (i -> i < finalTable.size()), (i -> ++i)) .forEach(a -> System.out.printf(formatString.toString(), finalTable.get(a))); for (String[] t: finalTable) { for (String a: t) { System.out.printf(formatString.toString(), t); } } */ finalTable.stream().forEach(a -> System.out.printf(formatString.toString(), a)); System.out.print(line); } private static List<String[]> prepareColumnTexts(List<String[]> table, int maxColumnWidth) { List<String[]> finalTableList = new ArrayList<>(); for (String[] row : table) { // If any cell data is more than max width, then it will need extra row. boolean needExtraRow = false; // Count of extra split row. int splitRow = 0; do { needExtraRow = false; String[] newRow = new String[row.length]; for (int i = 0; i < row.length; i++) { // If data is less than max width, use that as it is. if (row[i] != null) { if (row[i].length() < maxColumnWidth) { newRow[i] = splitRow == 0 ? row[i] : ""; } else if ((row[i].length() > (splitRow * maxColumnWidth))) { // If data is more than max width, then crop data at maxColumnWidth. // Remaining cropped data will be part of next row. int end = row[i].length() > ((splitRow * maxColumnWidth) + maxColumnWidth) ? (splitRow * maxColumnWidth) + maxColumnWidth : row[i].length(); newRow[i] = row[i].substring((splitRow * maxColumnWidth), end); needExtraRow = true; } else { newRow[i] = ""; } } else { newRow[i] = row[i]; } } finalTableList.add(newRow); if (needExtraRow) { splitRow++; } } while (needExtraRow); } String[][] finalTable = new String[finalTableList.size()][finalTableList.get(0).length]; for (int i = 0; i < finalTable.length; i++) { finalTable[i] = finalTableList.get(i); } return finalTableList; } private static String buildDemarcationLine(Map<Integer, Integer> columnLengths) { /* * Prepare line for top, bottom & below header row. StringBuffer line = new StringBuffer(columnLengths.entrySet().stream().reduce("", (ln, b) -> { StringBuffer templn = new StringBuffer("+-"); templn.append(Stream.iterate(0, (i -> i < b.getValue()), (i -> ++i)).reduce("", (ln1, b1) -> ln1 + "-", (a1, b1) -> a1 + b1)); templn.append("-"); return ln + templn; }, (a, b) -> a + b)); line.append("+\n"); return line.toString(); */ StringBuffer templn = new StringBuffer("+-"); for (Integer e: columnLengths.keySet()) { Integer length = columnLengths.get(e); for (int i = 0; i < length; ++i) { templn.append("-"); } templn.append("+-"); } templn.append("\n"); return templn.toString(); } private static Map<Integer, Integer> calculateColumnsLength(List<String[]> table) { /* * Calculate appropriate Length of each column by looking at width of data in * each column. * * Map columnLengths is <column_number, column_length> */ Map<Integer, Integer> columnLengths = new HashMap<>(); for (String[] row: table) { int i = 0; for (String col : row) { if (columnLengths.get(i) == null) { columnLengths.put(i, 0); } if (col != null) { if (columnLengths.get(i) < col.length()) { columnLengths.put(i, col.length()); } } i++; } } /* table.forEach(a -> Stream.iterate(0, (i -> i < a.length), (i -> ++i)).forEach(i -> { if (columnLengths.get(i) == null) { columnLengths.put(i, 0); } if (a[i] != null) { if (columnLengths.get(i) < a[i].length()) { columnLengths.put(i, a[i].length()); } } })); */ return columnLengths; } private static StringBuilder buildFormatString(Map<Integer, Integer> columnLengths) { /* * Prepare format String */ final StringBuilder formatString = new StringBuilder(""); String flag = leftJustifiedRows ? "-" : ""; columnLengths.entrySet().stream().forEach(e -> formatString.append("| %" + flag + e.getValue() + "s ")); formatString.append("|\n"); return formatString; } public static void testFunc() { /* * Sample Table to print in console in 2-dimensional array. Each sub-array is a * row. */ String[][] table = new String[][] { { "id", "First Name", "Last Name", "Age", "Profile" }, { "1", "John", "Johnson", "45", "My name is John Johnson. My id is 1. My age is 45." }, { "2", "Tom", "", "35", "My name is Tom. My id is 2. My age is 35." }, { "3", "Rose", "Johnson Johnson Johnson Johnson Johnson Johnson Johnson Johnson Johnson Johnson", "22", "My name is Rose Johnson. My id is 3. My age is 22." }, { "4", "Jimmy", "Kimmel", "", "My name is Jimmy Kimmel. My id is 4. My age is not specified. " + "I am the host of the late night show. I am not fan of Matt Damon. " } }; /* * Create new table array with wrapped rows */ ArrayList<String[]> tableList = new ArrayList<>(Arrays.asList(table)); // Input formatIntoTable(tableList); } }
cckmit/zingg
client/src/main/java/zingg/client/util/CliUtils.java
214,006
/* * Copyright (c) 2010-2012 Engine Yard, Inc. * Copyright (c) 2007-2009 Sun Microsystems, Inc. * This source code is available under the MIT license. * See the file LICENSE.txt for details. * * 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.jruby.rack.mock; import java.io.Serializable; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Vector; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; import javax.servlet.http.HttpSessionContext; /** * Mock implementation of the {@link javax.servlet.http.HttpSession} interface. * * <p>Compatible with Servlet 2.5 as well as Servlet 3.0. * * @author Juergen Hoeller * @author Rod Johnson * @author Mark Fisher */ @SuppressWarnings("deprecation") public class MockHttpSession implements HttpSession { private static int nextId = 1; private String id; private final long creationTime = System.currentTimeMillis(); private int maxInactiveInterval; private long lastAccessedTime = System.currentTimeMillis(); private final ServletContext servletContext; private final Map<String, Object> attributes = new LinkedHashMap<String, Object>(); private boolean invalid = false; private boolean isNew = true; /** * Create a new MockHttpSession with a default {@link MockServletContext}. * * @see MockServletContext */ public MockHttpSession() { this(null); } /** * Create a new MockHttpSession. * * @param servletContext the ServletContext that the session runs in */ public MockHttpSession(ServletContext servletContext) { this(servletContext, null); } /** * Create a new MockHttpSession. * * @param servletContext the ServletContext that the session runs in * @param id a unique identifier for this session */ public MockHttpSession(ServletContext servletContext, String id) { this.servletContext = servletContext; this.id = (id != null ? id : Integer.toString(nextId++)); } public long getCreationTime() throws IllegalStateException { checkInvalid("getCreationTime()"); return this.creationTime; } public String getId() { return this.id; } void setId(String id) { this.id = id; } public void access() { this.lastAccessedTime = System.currentTimeMillis(); this.isNew = false; } public long getLastAccessedTime() throws IllegalStateException { checkInvalid("getLastAccessedTime()"); return this.lastAccessedTime; } public ServletContext getServletContext() { return this.servletContext; } public void setMaxInactiveInterval(int interval) { this.maxInactiveInterval = interval; } public int getMaxInactiveInterval() { return this.maxInactiveInterval; } public HttpSessionContext getSessionContext() { throw new UnsupportedOperationException("getSessionContext"); } public Object getAttribute(String name) throws IllegalStateException { checkInvalid("getAttribute("+ name +")"); return this.attributes.get(name); } public Object getValue(String name) { return getAttribute(name); } public Enumeration<String> getAttributeNames() throws IllegalStateException { checkInvalid("getAttributeNames()"); return new Vector<String>(this.attributes.keySet()).elements(); } public String[] getValueNames() throws IllegalStateException { checkInvalid("getValueNames()"); return this.attributes.keySet().toArray(new String[this.attributes.size()]); } public void setAttribute(String name, Object value) throws IllegalStateException { checkInvalid("setAttribute("+ name + ")"); if (value != null) { this.attributes.put(name, value); if (value instanceof HttpSessionBindingListener) { ((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value)); } } else { removeAttribute(name); } } public void putValue(String name, Object value) { setAttribute(name, value); } public void removeAttribute(String name) throws IllegalStateException { checkInvalid("removeAttribute("+ name + ")"); Object value = this.attributes.remove(name); if (value instanceof HttpSessionBindingListener) { ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value)); } } public void removeValue(String name) { removeAttribute(name); } /** * Clear all of this session's attributes. */ public void clearAttributes() { for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) { Map.Entry<String, Object> entry = it.next(); String name = entry.getKey(); Object value = entry.getValue(); it.remove(); if (value instanceof HttpSessionBindingListener) { ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value)); } } } public void invalidate() throws IllegalStateException { checkInvalid("invalidate()"); this.invalid = true; clearAttributes(); } public boolean isInvalid() { return this.invalid; } public void setNew(boolean value) { this.isNew = value; } public boolean isNew() throws IllegalStateException { checkInvalid("isNew()"); return this.isNew; } /** * Serialize the attributes of this session into an object that can be * turned into a byte array with standard Java serialization. * * @return a representation of this session's serialized state */ public Serializable serializeState() { HashMap<String, Serializable> state = new HashMap<String, Serializable>(); for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) { Map.Entry<String, Object> entry = it.next(); String name = entry.getKey(); Object value = entry.getValue(); it.remove(); if (value instanceof Serializable) { state.put(name, (Serializable) value); } else { // Not serializable... Servlet containers usually automatically // unbind the attribute in this case. if (value instanceof HttpSessionBindingListener) { ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value)); } } } return state; } /** * Deserialize the attributes of this session from a state object created by * {@link #serializeState()}. * * @param state a representation of this session's serialized state */ @SuppressWarnings("unchecked") public void deserializeState(Serializable state) { this.attributes.putAll((Map<String, Object>) state); } @Override public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()) + this.attributes; } Map<String, Object> getAttributes() { return attributes; } private void checkInvalid(String method) throws IllegalStateException { if ( invalid == true ) { if ( method == null ) method = ""; throw new IllegalStateException(method + ": session already invalidated"); } } }
jruby/jruby-rack
src/spec/java/org/jruby/rack/mock/MockHttpSession.java
214,007
package mage.cards.r; import mage.MageInt; import mage.abilities.common.AttacksTriggeredAbility; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.common.PayEnergyCost; import mage.abilities.dynamicvalue.common.CardsInControllerHandCount; import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount; import mage.abilities.effects.common.DoIfCostPaid; import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.abilities.effects.common.continuous.SetBasePowerSourceEffect; import mage.abilities.effects.common.counter.GetEnergyCountersControllerEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.TargetController; import mage.constants.Zone; import mage.filter.FilterPermanent; import mage.filter.common.FilterArtifactCreaturePermanent; import java.util.UUID; /** * * @author justinjohnson14 */ public final class RobobrainWarMind extends CardImpl { private static final FilterPermanent filter = new FilterArtifactCreaturePermanent(); static { filter.add(TargetController.YOU.getControllerPredicate()); } public RobobrainWarMind(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{3}{U}"); this.subtype.add(SubType.ROBOT); this.power = new MageInt(0); this.toughness = new MageInt(5); // Robobrain War Mind's power is equal to the number of cards in your hand. this.addAbility(new SimpleStaticAbility(Zone.ALL, new SetBasePowerSourceEffect(CardsInControllerHandCount.instance))); // When Robobrain War Mind enters the battlefield, you get an amount of {E} equal to the number of artifact creatures you control. this.addAbility(new EntersBattlefieldTriggeredAbility(new GetEnergyCountersControllerEffect(new PermanentsOnBattlefieldCount(filter)) .setText("you get an amount of {E} equal to the number of artifact creatures you control"))); // Whenever Robobrain War Mind attacks, you may pay {E}{E}{E}. If you do, draw a card. this.addAbility(new AttacksTriggeredAbility(new DoIfCostPaid(new DrawCardSourceControllerEffect(1), new PayEnergyCost(3)))); } private RobobrainWarMind(final RobobrainWarMind card) { super(card); } @Override public RobobrainWarMind copy() { return new RobobrainWarMind(this); } }
magefree/mage
Mage.Sets/src/mage/cards/r/RobobrainWarMind.java
214,008
/* * * This file is part of the iText (R) project. * Copyright (c) 2014-2015 iText Group NV * Authors: Bruno Lowagie, Paulo Soares, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: * http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, * a covered work must retain the producer line in every PDF that is created * or manipulated using iText. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the iText software without * disclosing the source code of your own applications. * These activities include: offering paid services to customers as an ASP, * serving PDFs on the fly in a web application, shipping iText with a closed * source product. * * For more information, please contact iText Software Corp. at this * address: [email protected] * * * This class is based on the C# open source freeware library Clipper: * http://www.angusj.com/delphi/clipper.php * The original classes were distributed under the Boost Software License: * * Freeware for both open source and commercial applications * Copyright 2010-2014 Angus Johnson * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.itextpdf.text.pdf.parser.clipper; import com.itextpdf.text.pdf.parser.clipper.Point.LongPoint; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; public abstract class ClipperBase implements Clipper { protected class LocalMinima { long y; Edge leftBound; Edge rightBound; LocalMinima next; }; protected class Scanbeam { long y; Scanbeam next; }; private static void initEdge( Edge e, Edge eNext, Edge ePrev, LongPoint pt ) { e.next = eNext; e.prev = ePrev; e.setCurrent( new LongPoint( pt ) ); e.outIdx = Edge.UNASSIGNED; } private static void initEdge2( Edge e, PolyType polyType ) { if (e.getCurrent().getY() >= e.next.getCurrent().getY()) { e.setBot( new LongPoint( e.getCurrent() ) ); e.setTop( new LongPoint( e.next.getCurrent() ) ); } else { e.setTop( new LongPoint( e.getCurrent() ) ); e.setBot( new LongPoint( e.next.getCurrent() ) ); } e.updateDeltaX(); e.polyTyp = polyType; } private static boolean rangeTest( LongPoint Pt, boolean useFullRange ) { if (useFullRange) { if (Pt.getX() > HI_RANGE || Pt.getY() > HI_RANGE || -Pt.getX() > HI_RANGE || -Pt.getY() > HI_RANGE) throw new IllegalStateException("Coordinate outside allowed range"); } else if (Pt.getX() > LOW_RANGE || Pt.getY() > LOW_RANGE || -Pt.getX() > LOW_RANGE || -Pt.getY() > LOW_RANGE) { return rangeTest(Pt, true); } return useFullRange; } private static Edge removeEdge( Edge e ) { //removes e from double_linked_list (but without removing from memory) e.prev.next = e.next; e.next.prev = e.prev; final Edge result = e.next; e.prev = null; //flag as removed (see ClipperBase.Clear) return result; } private final static long LOW_RANGE = 0x3FFFFFFF; private final static long HI_RANGE = 0x3FFFFFFFFFFFFFFFL; protected LocalMinima minimaList; protected LocalMinima currentLM; private final List<List<Edge>> edges; protected boolean useFullRange; protected boolean hasOpenPaths; protected final boolean preserveCollinear; private final static Logger LOGGER = Logger.getLogger( Clipper.class.getName() ); protected ClipperBase( boolean preserveCollinear ) //constructor (nb: no external instantiation) { this.preserveCollinear = preserveCollinear; minimaList = null; currentLM = null; hasOpenPaths = false; edges = new ArrayList<List<Edge>>(); } public boolean addPath( Path pg, PolyType polyType, boolean Closed ) { if (!Closed && polyType == PolyType.CLIP) { throw new IllegalStateException( "AddPath: Open paths must be subject." ); } int highI = pg.size() - 1; if (Closed) { while (highI > 0 && pg.get( highI ).equals( pg.get( 0 ) )) { --highI; } } while (highI > 0 && pg.get( highI ).equals( pg.get( highI - 1 ) )) { --highI; } if (Closed && highI < 2 || !Closed && highI < 1) { return false; } //create a new edge array ... final List<Edge> edges = new ArrayList<Edge>( highI + 1 ); for (int i = 0; i <= highI; i++) { edges.add( new Edge() ); } boolean IsFlat = true; //1. Basic (first) edge initialization ... edges.get( 1 ).setCurrent( new LongPoint( pg.get( 1 ) ) ); useFullRange = rangeTest( pg.get( 0 ), useFullRange ); useFullRange = rangeTest( pg.get( highI ), useFullRange ); initEdge( edges.get( 0 ), edges.get( 1 ), edges.get( highI ), pg.get( 0 ) ); initEdge( edges.get( highI ), edges.get( 0 ), edges.get( highI - 1 ), pg.get( highI ) ); for (int i = highI - 1; i >= 1; --i) { useFullRange = rangeTest( pg.get( i ), useFullRange ); initEdge( edges.get( i ), edges.get( i + 1 ), edges.get( i - 1 ), pg.get( i ) ); } Edge eStart = edges.get( 0 ); //2. Remove duplicate vertices, and (when closed) collinear edges ... Edge e = eStart, eLoopStop = eStart; for (;;) { //nb: allows matching start and end points when not Closed ... if (e.getCurrent().equals( e.next.getCurrent() ) && (Closed || !e.next.equals( eStart ))) { if (e == e.next) { break; } if (e == eStart) { eStart = e.next; } e = removeEdge( e ); eLoopStop = e; continue; } if (e.prev == e.next) { break; //only two vertices } else if (Closed && Point.slopesEqual( e.prev.getCurrent(), e.getCurrent(), e.next.getCurrent(), useFullRange ) && (!isPreserveCollinear() || !Point.isPt2BetweenPt1AndPt3( e.prev.getCurrent(), e.getCurrent(), e.next.getCurrent() ))) { //Collinear edges are allowed for open paths but in closed paths //the default is to merge adjacent collinear edges into a single edge. //However, if the PreserveCollinear property is enabled, only overlapping //collinear edges (ie spikes) will be removed from closed paths. if (e == eStart) { eStart = e.next; } e = removeEdge( e ); e = e.prev; eLoopStop = e; continue; } e = e.next; if (e == eLoopStop || !Closed && e.next == eStart) { break; } } if (!Closed && e == e.next || Closed && e.prev == e.next) { return false; } if (!Closed) { hasOpenPaths = true; eStart.prev.outIdx = Edge.SKIP; } //3. Do second stage of edge initialization ... e = eStart; do { initEdge2( e, polyType ); e = e.next; if (IsFlat && e.getCurrent().getY() != eStart.getCurrent().getY()) { IsFlat = false; } } while (e != eStart); //4. Finally, add edge bounds to LocalMinima list ... //Totally flat paths must be handled differently when adding them //to LocalMinima list to avoid endless loops etc ... if (IsFlat) { if (Closed) { return false; } e.prev.outIdx = Edge.SKIP; final LocalMinima locMin = new LocalMinima(); locMin.next = null; locMin.y = e.getBot().getY(); locMin.leftBound = null; locMin.rightBound = e; locMin.rightBound.side = Edge.Side.RIGHT; locMin.rightBound.windDelta = 0; for ( ; ; ) { if (e.getBot().getX() != e.prev.getTop().getX()) e.reverseHorizontal(); if (e.next.outIdx == Edge.SKIP) break; e.nextInLML = e.next; e = e.next; } insertLocalMinima( locMin ); this.edges.add( edges ); return true; } this.edges.add( edges ); boolean leftBoundIsForward; Edge EMin = null; //workaround to avoid an endless loop in the while loop below when //open paths have matching start and end points ... if (e.prev.getBot().equals( e.prev.getTop() )) { e = e.next; } for (;;) { e = e.findNextLocMin(); if (e == EMin) { break; } else if (EMin == null) { EMin = e; } //E and E.Prev now share a local minima (left aligned if horizontal). //Compare their slopes to find which starts which bound ... final LocalMinima locMin = new LocalMinima(); locMin.next = null; locMin.y = e.getBot().getY(); if (e.deltaX < e.prev.deltaX) { locMin.leftBound = e.prev; locMin.rightBound = e; leftBoundIsForward = false; //Q.nextInLML = Q.prev } else { locMin.leftBound = e; locMin.rightBound = e.prev; leftBoundIsForward = true; //Q.nextInLML = Q.next } locMin.leftBound.side = Edge.Side.LEFT; locMin.rightBound.side = Edge.Side.RIGHT; if (!Closed) { locMin.leftBound.windDelta = 0; } else if (locMin.leftBound.next == locMin.rightBound) { locMin.leftBound.windDelta = -1; } else { locMin.leftBound.windDelta = 1; } locMin.rightBound.windDelta = -locMin.leftBound.windDelta; e = processBound( locMin.leftBound, leftBoundIsForward ); if (e.outIdx == Edge.SKIP) { e = processBound( e, leftBoundIsForward ); } Edge E2 = processBound( locMin.rightBound, !leftBoundIsForward ); if (E2.outIdx == Edge.SKIP) { E2 = processBound( E2, !leftBoundIsForward ); } if (locMin.leftBound.outIdx == Edge.SKIP) { locMin.leftBound = null; } else if (locMin.rightBound.outIdx == Edge.SKIP) { locMin.rightBound = null; } insertLocalMinima( locMin ); if (!leftBoundIsForward) { e = E2; } } return true; } public boolean addPaths( Paths ppg, PolyType polyType, boolean closed ) { boolean result = false; for (int i = 0; i < ppg.size(); ++i) { if (addPath( ppg.get( i ), polyType, closed )) { result = true; } } return result; } public void clear() { disposeLocalMinimaList(); edges.clear(); useFullRange = false; hasOpenPaths = false; } private void disposeLocalMinimaList() { while (minimaList != null) { final LocalMinima tmpLm = minimaList.next; minimaList = null; minimaList = tmpLm; } currentLM = null; } private void insertLocalMinima( LocalMinima newLm ) { if (minimaList == null) { minimaList = newLm; } else if (newLm.y >= minimaList.y) { newLm.next = minimaList; minimaList = newLm; } else { LocalMinima tmpLm = minimaList; while (tmpLm.next != null && newLm.y < tmpLm.next.y) { tmpLm = tmpLm.next; } newLm.next = tmpLm.next; tmpLm.next = newLm; } } public boolean isPreserveCollinear() { return preserveCollinear; } protected void popLocalMinima() { LOGGER.entering( ClipperBase.class.getName(), "popLocalMinima" ); if (currentLM == null) { return; } currentLM = currentLM.next; } private Edge processBound( Edge e, boolean LeftBoundIsForward ) { Edge EStart, result = e; Edge Horz; if (result.outIdx == Edge.SKIP) { //check if there are edges beyond the skip edge in the bound and if so //create another LocMin and calling ProcessBound once more ... e = result; if (LeftBoundIsForward) { while (e.getTop().getY() == e.next.getBot().getY()) { e = e.next; } while (e != result && e.deltaX == Edge.HORIZONTAL) { e = e.prev; } } else { while (e.getTop().getY() == e.prev.getBot().getY()) { e = e.prev; } while (e != result && e.deltaX == Edge.HORIZONTAL) { e = e.next; } } if (e == result) { if (LeftBoundIsForward) { result = e.next; } else { result = e.prev; } } else { //there are more edges in the bound beyond result starting with E if (LeftBoundIsForward) { e = result.next; } else { e = result.prev; } final LocalMinima locMin = new LocalMinima(); locMin.next = null; locMin.y = e.getBot().getY(); locMin.leftBound = null; locMin.rightBound = e; e.windDelta = 0; result = processBound( e, LeftBoundIsForward ); insertLocalMinima( locMin ); } return result; } if (e.deltaX == Edge.HORIZONTAL) { //We need to be careful with open paths because this may not be a //true local minima (ie E may be following a skip edge). //Also, consecutive horz. edges may start heading left before going right. if (LeftBoundIsForward) { EStart = e.prev; } else { EStart = e.next; } if (EStart.deltaX == Edge.HORIZONTAL) //ie an adjoining horizontal skip edge { if (EStart.getBot().getX() != e.getBot().getX() && EStart.getTop().getX() != e.getBot().getX()) e.reverseHorizontal(); } else if (EStart.getBot().getX() != e.getBot().getX()) e.reverseHorizontal(); } EStart = e; if (LeftBoundIsForward) { while (result.getTop().getY() == result.next.getBot().getY() && result.next.outIdx != Edge.SKIP) { result = result.next; } if (result.deltaX == Edge.HORIZONTAL && result.next.outIdx != Edge.SKIP) { //nb: at the top of a bound, horizontals are added to the bound //only when the preceding edge attaches to the horizontal's left vertex //unless a Skip edge is encountered when that becomes the top divide Horz = result; while (Horz.prev.deltaX == Edge.HORIZONTAL) { Horz = Horz.prev; } if (Horz.prev.getTop().getX() > result.next.getTop().getX()) result = Horz.prev; } while (e != result) { e.nextInLML = e.next; if (e.deltaX == Edge.HORIZONTAL && e != EStart && e.getBot().getX() != e.prev.getTop().getX()) { e.reverseHorizontal(); } e = e.next; } if (e.deltaX == Edge.HORIZONTAL && e != EStart && e.getBot().getX() != e.prev.getTop().getX()) { e.reverseHorizontal(); } result = result.next; //move to the edge just beyond current bound } else { while (result.getTop().getY() == result.prev.getBot().getY() && result.prev.outIdx != Edge.SKIP) { result = result.prev; } if (result.deltaX == Edge.HORIZONTAL && result.prev.outIdx != Edge.SKIP) { Horz = result; while (Horz.next.deltaX == Edge.HORIZONTAL) { Horz = Horz.next; } if (Horz.next.getTop().getX() == result.prev.getTop().getX() || Horz.next.getTop().getX() > result.prev.getTop().getX()) result = Horz.next; } while (e != result) { e.nextInLML = e.prev; if (e.deltaX == Edge.HORIZONTAL && e != EStart && e.getBot().getX() != e.next.getTop().getX()) { e.reverseHorizontal(); } e = e.prev; } if (e.deltaX == Edge.HORIZONTAL && e != EStart && e.getBot().getX() != e.next.getTop().getX()) { e.reverseHorizontal(); } result = result.prev; //move to the edge just beyond current bound } return result; } protected static Path.OutRec parseFirstLeft(Path.OutRec FirstLeft) { while (FirstLeft != null && FirstLeft.getPoints() == null) FirstLeft = FirstLeft.firstLeft; return FirstLeft; } protected void reset() { currentLM = minimaList; if (currentLM == null) { return; //ie nothing to process } //reset all edges ... LocalMinima lm = minimaList; while (lm != null) { Edge e = lm.leftBound; if (e != null) { e.setCurrent( new LongPoint( e.getBot() ) ); e.side = Edge.Side.LEFT; e.outIdx = Edge.UNASSIGNED; } e = lm.rightBound; if (e != null) { e.setCurrent( new LongPoint( e.getBot() ) ); e.side = Edge.Side.RIGHT; e.outIdx = Edge.UNASSIGNED; } lm = lm.next; } } }
jieWang0/itextpdf
itext/src/main/java/com/itextpdf/text/pdf/parser/clipper/ClipperBase.java
214,011
// ======================================================================== // $Id: DateCache.java,v 1.15 2004/05/09 20:32:49 gregwilkins Exp $ // Copyright 1996-2004 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== package net.lightbody.bmp.proxy.jetty.util; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /* ------------------------------------------------------------ */ /** Date Format Cache. * Computes String representations of Dates and caches * the results so that subsequent requests within the same minute * will be fast. * * Only format strings that contain either "ss" or "ss.SSS" are * handled. * * The timezone of the date may be included as an ID with the "zzz" * format string or as an offset with the "ZZZ" format string. * * If consecutive calls are frequently very different, then this * may be a little slower than a normal DateFormat. * * @version $Id: DateCache.java,v 1.15 2004/05/09 20:32:49 gregwilkins Exp $ * @author Kent Johnson <[email protected]> * @author Greg Wilkins (gregw) */ public class DateCache { private static long __hitWindow=60*60; private static long __MaxMisses=10; private String _formatString; private String _tzFormatString; private SimpleDateFormat _tzFormat; private String _minFormatString; private SimpleDateFormat _minFormat; private String _secFormatString; private String _secFormatString0; private String _secFormatString1; private boolean _millis=false; private long _misses = 0; private long _lastMinutes = -1; private long _lastSeconds = -1; private String _lastResult = null; private Locale _locale = null; private DateFormatSymbols _dfs = null; /* ------------------------------------------------------------ */ /** Constructor. * Make a DateCache that will use a default format. The default format * generates the same results as Date.toString(). */ public DateCache() { this("EEE MMM dd HH:mm:ss zzz yyyy"); getFormat().setTimeZone(TimeZone.getDefault()); } /* ------------------------------------------------------------ */ /** Constructor. * Make a DateCache that will use the given format */ public DateCache(String format) { _formatString=format; setTimeZone(TimeZone.getDefault()); } /* ------------------------------------------------------------ */ public DateCache(String format,Locale l) { _formatString=format; _locale = l; setTimeZone(TimeZone.getDefault()); } /* ------------------------------------------------------------ */ public DateCache(String format,DateFormatSymbols s) { _formatString=format; _dfs = s; setTimeZone(TimeZone.getDefault()); } /* ------------------------------------------------------------ */ /** Set the timezone. * @param tz TimeZone */ public void setTimeZone(TimeZone tz) { setTzFormatString(tz); if( _locale != null ) { _tzFormat=new SimpleDateFormat(_tzFormatString,_locale); _minFormat=new SimpleDateFormat(_minFormatString,_locale); } else if( _dfs != null ) { _tzFormat=new SimpleDateFormat(_tzFormatString,_dfs); _minFormat=new SimpleDateFormat(_minFormatString,_dfs); } else { _tzFormat=new SimpleDateFormat(_tzFormatString); _minFormat=new SimpleDateFormat(_minFormatString); } _tzFormat.setTimeZone(tz); _minFormat.setTimeZone(tz); _lastSeconds=-1; _lastMinutes=-1; } /* ------------------------------------------------------------ */ public TimeZone getTimeZone() { return _tzFormat.getTimeZone(); } /* ------------------------------------------------------------ */ /** Set the timezone. * @param timeZoneId TimeZoneId the ID of the zone as used by * TimeZone.getTimeZone(id) */ public void setTimeZoneID(String timeZoneId) { setTimeZone(TimeZone.getTimeZone(timeZoneId)); } /* ------------------------------------------------------------ */ private void setTzFormatString(final TimeZone tz ) { int zIndex = _formatString.indexOf( "ZZZ" ); if( zIndex >= 0 ) { String ss1 = _formatString.substring( 0, zIndex ); String ss2 = _formatString.substring( zIndex+3 ); int tzOffset = tz.getRawOffset(); StringBuffer sb = new StringBuffer(_formatString.length()+10); sb.append(ss1); sb.append("'"); if( tzOffset >= 0 ) sb.append( '+' ); else { tzOffset = -tzOffset; sb.append( '-' ); } int raw = tzOffset / (1000*60); // Convert to seconds int hr = raw / 60; int min = raw % 60; if( hr < 10 ) sb.append( '0' ); sb.append( hr ); if( min < 10 ) sb.append( '0' ); sb.append( min ); sb.append( '\'' ); sb.append(ss2); _tzFormatString=sb.toString(); } else _tzFormatString=_formatString; setMinFormatString(); } /* ------------------------------------------------------------ */ private void setMinFormatString() { int i = _tzFormatString.indexOf("ss.SSS"); int l = 6; if (i>=0) _millis=true; else { i = _tzFormatString.indexOf("ss"); l=2; } // Build a formatter that formats a second format string // Have to replace @ with ' later due to bug in SimpleDateFormat String ss1=_tzFormatString.substring(0,i); String ss2=_tzFormatString.substring(i+l); _minFormatString =ss1+(_millis?"'ss.SSS'":"'ss'")+ss2; } /* ------------------------------------------------------------ */ /** Format a date according to our stored formatter. * @param inDate * @return Formatted date */ public synchronized String format(Date inDate) { return format(inDate.getTime()); } /* ------------------------------------------------------------ */ /** Format a date according to our stored formatter. * @param inDate * @return Formatted date */ public synchronized String format(long inDate) { long seconds = inDate / 1000; // Is it not suitable to cache? if (seconds<_lastSeconds || _lastSeconds>0 && seconds>_lastSeconds+__hitWindow) { // It's a cache miss _misses++; if (_misses<__MaxMisses) { Date d = new Date(inDate); return _tzFormat.format(d); } } else if (_misses>0) _misses--; // Check if we are in the same second // and don't care about millis if (_lastSeconds==seconds && !_millis) return _lastResult; Date d = new Date(inDate); // Check if we need a new format string long minutes = seconds/60; if (_lastMinutes != minutes) { _lastMinutes = minutes; _secFormatString=_minFormat.format(d); int i; int l; if (_millis) { i=_secFormatString.indexOf("ss.SSS"); l=6; } else { i=_secFormatString.indexOf("ss"); l=2; } _secFormatString0=_secFormatString.substring(0,i); _secFormatString1=_secFormatString.substring(i+l); } // Always format if we get here _lastSeconds = seconds; StringBuffer sb=new StringBuffer(_secFormatString.length()); synchronized(sb) { sb.append(_secFormatString0); int s=(int)(seconds%60); if (s<10) sb.append('0'); sb.append(s); if (_millis) { long millis = inDate%1000; if (millis<10) sb.append(".00"); else if (millis<100) sb.append(".0"); else sb.append('.'); sb.append(millis); } sb.append(_secFormatString1); _lastResult=sb.toString(); } return _lastResult; } /* ------------------------------------------------------------ */ /** Format to string buffer. * @param inDate Date the format * @param buffer StringBuffer */ public void format(long inDate, StringBuffer buffer) { buffer.append(format(inDate)); } /* ------------------------------------------------------------ */ /** Get the format. */ public SimpleDateFormat getFormat() { return _minFormat; } /* ------------------------------------------------------------ */ public String getFormatString() { return _formatString; } }
lightbody/browsermob-proxy
browsermob-legacy/src/main/java/net/lightbody/bmp/proxy/jetty/util/DateCache.java
214,012
/** * Copyright (c) 2010-2024 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.somfymylink.internal.model; import org.eclipse.jdt.annotation.NonNullByDefault; /** * @author Chris Johnson - Initial contribution */ @NonNullByDefault public class SomfyMyLinkCommandSceneParams extends SomfyMyLinkCommandParamsBase { public final int sceneId; public SomfyMyLinkCommandSceneParams(int sceneId, String auth) { super(auth); this.sceneId = sceneId; } }
mhilbush/openhab-addons
bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/model/SomfyMyLinkCommandSceneParams.java
214,013
/* NOTICE: This file has been changed by Plutext Pty Ltd for use in docx4j. * The package name has been changed; there may also be other changes. * * This notice is included to meet the condition in clause 4(b) of the License. */ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.docx4j.org.apache.poi.util; /** * A List of int's; as full an implementation of the java.util.List * interface as possible, with an eye toward minimal creation of * objects * * the mimicry of List is as follows: * <ul> * <li> if possible, operations designated 'optional' in the List * interface are attempted * <li> wherever the List interface refers to an Object, substitute * int * <li> wherever the List interface refers to a Collection or List, * substitute IntList * </ul> * * the mimicry is not perfect, however: * <ul> * <li> operations involving Iterators or ListIterators are not * supported * <li> remove(Object) becomes removeValue to distinguish it from * remove(int index) * <li> subList is not supported * </ul> * * @author Marc Johnson */ public class IntList { private int[] _array; private int _limit; private int fillval = 0; private static final int _default_size = 128; /** * create an IntList of default size */ public IntList() { this(_default_size); } public IntList(final int initialCapacity) { this(initialCapacity,0); } /** * create a copy of an existing IntList * * @param list the existing IntList */ public IntList(final IntList list) { this(list._array.length); System.arraycopy(list._array, 0, _array, 0, _array.length); _limit = list._limit; } /** * create an IntList with a predefined initial size * * @param initialCapacity the size for the internal array */ public IntList(final int initialCapacity, int fillvalue) { _array = new int[ initialCapacity ]; if (fillval != 0) { fillval = fillvalue; fillArray(fillval, _array, 0); } _limit = 0; } private void fillArray(int val, int[] array, int index) { for (int k = index; k < array.length; k++) { array[k] = val; } } /** * add the specfied value at the specified index * * @param index the index where the new value is to be added * @param value the new value * * @exception IndexOutOfBoundsException if the index is out of * range (index < 0 || index > size()). */ public void add(final int index, final int value) { if (index > _limit) { throw new IndexOutOfBoundsException(); } else if (index == _limit) { add(value); } else { // index < limit -- insert into the middle if (_limit == _array.length) { growArray(_limit * 2); } System.arraycopy(_array, index, _array, index + 1, _limit - index); _array[ index ] = value; _limit++; } } /** * Appends the specified element to the end of this list * * @param value element to be appended to this list. * * @return true (as per the general contract of the Collection.add * method). */ public boolean add(final int value) { if (_limit == _array.length) { growArray(_limit * 2); } _array[ _limit++ ] = value; return true; } /** * Appends all of the elements in the specified collection to the * end of this list, in the order that they are returned by the * specified collection's iterator. The behavior of this * operation is unspecified if the specified collection is * modified while the operation is in progress. (Note that this * will occur if the specified collection is this list, and it's * nonempty.) * * @param c collection whose elements are to be added to this * list. * * @return true if this list changed as a result of the call. */ public boolean addAll(final IntList c) { if (c._limit != 0) { if ((_limit + c._limit) > _array.length) { growArray(_limit + c._limit); } System.arraycopy(c._array, 0, _array, _limit, c._limit); _limit += c._limit; } return true; } /** * Inserts all of the elements in the specified collection into * this list at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements * to the right (increases their indices). The new elements will * appear in this list in the order that they are returned by the * specified collection's iterator. The behavior of this * operation is unspecified if the specified collection is * modified while the operation is in progress. (Note that this * will occur if the specified collection is this list, and it's * nonempty.) * * @param index index at which to insert first element from the * specified collection. * @param c elements to be inserted into this list. * * @return true if this list changed as a result of the call. * * @exception IndexOutOfBoundsException if the index is out of * range (index < 0 || index > size()) */ public boolean addAll(final int index, final IntList c) { if (index > _limit) { throw new IndexOutOfBoundsException(); } if (c._limit != 0) { if ((_limit + c._limit) > _array.length) { growArray(_limit + c._limit); } // make a hole System.arraycopy(_array, index, _array, index + c._limit, _limit - index); // fill it in System.arraycopy(c._array, 0, _array, index, c._limit); _limit += c._limit; } return true; } /** * Removes all of the elements from this list. This list will be * empty after this call returns (unless it throws an exception). */ public void clear() { _limit = 0; } /** * Returns true if this list contains the specified element. More * formally, returns true if and only if this list contains at * least one element e such that o == e * * @param o element whose presence in this list is to be tested. * * @return true if this list contains the specified element. */ public boolean contains(final int o) { boolean rval = false; for (int j = 0; !rval && (j < _limit); j++) { if (_array[ j ] == o) { rval = true; } } return rval; } /** * Returns true if this list contains all of the elements of the * specified collection. * * @param c collection to be checked for containment in this list. * * @return true if this list contains all of the elements of the * specified collection. */ public boolean containsAll(final IntList c) { boolean rval = true; if (this != c) { for (int j = 0; rval && (j < c._limit); j++) { if (!contains(c._array[ j ])) { rval = false; } } } return rval; } /** * Compares the specified object with this list for equality. * Returns true if and only if the specified object is also a * list, both lists have the same size, and all corresponding * pairs of elements in the two lists are equal. (Two elements e1 * and e2 are equal if e1 == e2.) In other words, two lists are * defined to be equal if they contain the same elements in the * same order. This definition ensures that the equals method * works properly across different implementations of the List * interface. * * @param o the object to be compared for equality with this list. * * @return true if the specified object is equal to this list. */ public boolean equals(final Object o) { boolean rval = this == o; if (!rval && (o != null) && (o.getClass() == this.getClass())) { IntList other = ( IntList ) o; if (other._limit == _limit) { // assume match rval = true; for (int j = 0; rval && (j < _limit); j++) { rval = _array[ j ] == other._array[ j ]; } } } return rval; } /** * Returns the element at the specified position in this list. * * @param index index of element to return. * * @return the element at the specified position in this list. * * @exception IndexOutOfBoundsException if the index is out of * range (index < 0 || index >= size()). */ public int get(final int index) { if (index >= _limit) { throw new IndexOutOfBoundsException( index + " not accessible in a list of length " + _limit ); } return _array[ index ]; } /** * Returns the hash code value for this list. The hash code of a * list is defined to be the result of the following calculation: * * <code> * hashCode = 1; * Iterator i = list.iterator(); * while (i.hasNext()) { * Object obj = i.next(); * hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode()); * } * </code> * * This ensures that list1.equals(list2) implies that * list1.hashCode()==list2.hashCode() for any two lists, list1 and * list2, as required by the general contract of Object.hashCode. * * @return the hash code value for this list. */ public int hashCode() { int hash = 0; for (int j = 0; j < _limit; j++) { hash = (31 * hash) + _array[ j ]; } return hash; } /** * Returns the index in this list of the first occurrence of the * specified element, or -1 if this list does not contain this * element. More formally, returns the lowest index i such that * (o == get(i)), or -1 if there is no such index. * * @param o element to search for. * * @return the index in this list of the first occurrence of the * specified element, or -1 if this list does not contain * this element. */ public int indexOf(final int o) { int rval = 0; for (; rval < _limit; rval++) { if (o == _array[ rval ]) { break; } } if (rval == _limit) { rval = -1; // didn't find it } return rval; } /** * Returns true if this list contains no elements. * * @return true if this list contains no elements. */ public boolean isEmpty() { return _limit == 0; } /** * Returns the index in this list of the last occurrence of the * specified element, or -1 if this list does not contain this * element. More formally, returns the highest index i such that * (o == get(i)), or -1 if there is no such index. * * @param o element to search for. * * @return the index in this list of the last occurrence of the * specified element, or -1 if this list does not contain * this element. */ public int lastIndexOf(final int o) { int rval = _limit - 1; for (; rval >= 0; rval--) { if (o == _array[ rval ]) { break; } } return rval; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from * their indices). Returns the element that was removed from the * list. * * @param index the index of the element to removed. * * @return the element previously at the specified position. * * @exception IndexOutOfBoundsException if the index is out of * range (index < 0 || index >= size()). */ public int remove(final int index) { if (index >= _limit) { throw new IndexOutOfBoundsException(); } int rval = _array[ index ]; System.arraycopy(_array, index + 1, _array, index, _limit - index); _limit--; return rval; } /** * Removes the first occurrence in this list of the specified * element (optional operation). If this list does not contain * the element, it is unchanged. More formally, removes the * element with the lowest index i such that (o.equals(get(i))) * (if such an element exists). * * @param o element to be removed from this list, if present. * * @return true if this list contained the specified element. */ public boolean removeValue(final int o) { boolean rval = false; for (int j = 0; !rval && (j < _limit); j++) { if (o == _array[ j ]) { if (j+1 < _limit) { System.arraycopy(_array, j + 1, _array, j, _limit - j); } _limit--; rval = true; } } return rval; } /** * Removes from this list all the elements that are contained in * the specified collection * * @param c collection that defines which elements will be removed * from this list. * * @return true if this list changed as a result of the call. */ public boolean removeAll(final IntList c) { boolean rval = false; for (int j = 0; j < c._limit; j++) { if (removeValue(c._array[ j ])) { rval = true; } } return rval; } /** * Retains only the elements in this list that are contained in * the specified collection. In other words, removes from this * list all the elements that are not contained in the specified * collection. * * @param c collection that defines which elements this set will * retain. * * @return true if this list changed as a result of the call. */ public boolean retainAll(final IntList c) { boolean rval = false; for (int j = 0; j < _limit; ) { if (!c.contains(_array[ j ])) { remove(j); rval = true; } else { j++; } } return rval; } /** * Replaces the element at the specified position in this list * with the specified element * * @param index index of element to replace. * @param element element to be stored at the specified position. * * @return the element previously at the specified position. * * @exception IndexOutOfBoundsException if the index is out of * range (index < 0 || index >= size()). */ public int set(final int index, final int element) { if (index >= _limit) { throw new IndexOutOfBoundsException(); } int rval = _array[ index ]; _array[ index ] = element; return rval; } /** * Returns the number of elements in this list. If this list * contains more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of elements in this IntList */ public int size() { return _limit; } /** * Returns an array containing all of the elements in this list in * proper sequence. Obeys the general contract of the * Collection.toArray method. * * @return an array containing all of the elements in this list in * proper sequence. */ public int [] toArray() { int[] rval = new int[ _limit ]; System.arraycopy(_array, 0, rval, 0, _limit); return rval; } /** * Returns an array containing all of the elements in this list in * proper sequence. Obeys the general contract of the * Collection.toArray(Object[]) method. * * @param a the array into which the elements of this list are to * be stored, if it is big enough; otherwise, a new array * is allocated for this purpose. * * @return an array containing the elements of this list. */ public int [] toArray(final int [] a) { int[] rval; if (a.length == _limit) { System.arraycopy(_array, 0, a, 0, _limit); rval = a; } else { rval = toArray(); } return rval; } private void growArray(final int new_size) { int size = (new_size == _array.length) ? new_size + 1 : new_size; int[] new_array = new int[ size ]; if (fillval != 0) { fillArray(fillval, new_array, _array.length); } System.arraycopy(_array, 0, new_array, 0, _limit); _array = new_array; } } // end public class IntList
plutext/docx4j
docx4j-core/src/main/java/org/docx4j/org/apache/poi/util/IntList.java
214,014
/* NOTICE: This file has been changed by Plutext Pty Ltd for use in docx4j. * The package name has been changed; there may also be other changes. * * This notice is included to meet the condition in clause 4(b) of the License. */ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.docx4j.org.apache.poi.poifs.property; import java.util.Iterator; import java.io.IOException; /** * Behavior for parent (directory) properties * * @author Marc [email protected] */ public interface Parent extends Child { /** * Get an iterator over the children of this Parent; all elements * are instances of Property. * * @return Iterator of children; may refer to an empty collection */ public Iterator getChildren(); /** * Add a new child to the collection of children * * @param property the new child to be added; must not be null * * @exception IOException if the Parent already has a child with * the same name */ public void addChild(final Property property) throws IOException; /** * Set the previous Child * * @param child the new 'previous' child; may be null, which has * the effect of saying there is no 'previous' child */ public void setPreviousChild(final Child child); /** * Set the next Child * * @param child the new 'next' child; may be null, which has the * effect of saying there is no 'next' child */ public void setNextChild(final Child child); /** *** end methods from interface Child *** */ } // end public interface Parent
plutext/docx4j
docx4j-core/src/main/java/org/docx4j/org/apache/poi/poifs/property/Parent.java
214,015
package com.baeldung.securityprofile; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.List; @RestController public class EmployeeController { @GetMapping("/employees") public List<String> getEmployees() { return Collections.singletonList("Adam Johnson"); } }
eugenp/tutorials
spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/securityprofile/EmployeeController.java
214,017
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.service.keybindings; import java.io.*; import java.text.*; import java.util.*; import javax.swing.*; /** * Convenience methods providing a quick means of loading and saving * keybindings. None preserve disabled mappings. The formats provided are as * follows:<br> * SERIAL_HASH- Serialized hash map of bindings. Ordering is preserved if * available.<br> * SERIAL_INPUT- Serialized input map of bindings.<br> * PROPERTIES_PAIR- Persistence provided by java.util.Properties using plain * text key/value pairs.<br> * PROPERTIES_XML- Persistence provided by java.util.Properties using its XML * format. * * @author Damian Johnson ([email protected]) * @version September 21, 2007 */ public enum Persistence { SERIAL_HASH, SERIAL_INPUT, PROPERTIES_PAIRS, PROPERTIES_XML; private static final String PROPERTIES_COMMENT = "Keybindings (mapping of KeyStrokes to string representations of actions)"; /** * Returns the enum representation of a string. This is case sensitive. * * @param str toString representation of this enum * @return enum associated with a string * @throws IllegalArgumentException if argument is not represented by this * enum. */ public static Persistence fromString(String str) { for (Persistence type : Persistence.values()) { if (str.equals(type.toString())) return type; } throw new IllegalArgumentException(); } /** * Attempts to load this type of persistent keystroke map from a given path. * This is unable to parse any null content. * * @param path absolute path to resource to be loaded * @return keybinding map reflecting file contents * @throws IOException if unable to load resource * @throws ParseException if unable to parse content */ public LinkedHashMap<KeyStroke, String> load(String path) throws IOException, ParseException { return load(new FileInputStream(path)); } /** * Attempts to load this type of persistent keystroke map from a given * stream. This is unable to parse any null content. * * @param input source of keybindings to be parsed * @return keybinding map reflecting file contents * @throws IOException if unable to load resource * @throws ParseException if unable to parse content */ public LinkedHashMap<KeyStroke, String> load(InputStream input) throws IOException, ParseException { LinkedHashMap<KeyStroke, String> output = new LinkedHashMap<KeyStroke, String>(); if (this == SERIAL_HASH || this == SERIAL_INPUT) { Object instance = null; // Loaded serialized object try { ObjectInputStream objectInput = new ObjectInputStream(input); instance = objectInput.readObject(); objectInput.close(); } catch (ClassNotFoundException exc) { throw new ParseException("Unable to load serialized content", 0); } if (this == SERIAL_HASH) { if (!(instance instanceof HashMap<?, ?>)) { throw new ParseException( "Serialized resource doesn't represent a HashMap", 0); } HashMap<?, ?> mapping = (HashMap<?, ?>)instance; for (Object key : mapping.keySet()) { Object value = mapping.get(key); if (key instanceof KeyStroke && value instanceof String) { output.put((KeyStroke) key, (String) value); } else { if (key == null || value == null) { throw new ParseException( "Unable to load null content", 0); } else { StringBuilder message = new StringBuilder(); message .append("Entry doesn't represent a keybinding: "); message.append(key.getClass().getName()); message.append(" -> "); message.append(value.getClass().getName()); message .append("\nMust match KeyStroke -> String mapping"); throw new ParseException(message.toString(), 0); } } } } else { if (!(instance instanceof InputMap)) { throw new ParseException( "Serialized resource doesn't represent an InputMap", 0); } InputMap mapping = (InputMap) instance; if (mapping.keys() != null) { for (KeyStroke shortcut : mapping.keys()) { if (shortcut == null || mapping.get(shortcut) == null) { throw new ParseException( "Unable to load null content", 0); } else { output.put(shortcut, mapping.get(shortcut) .toString()); } } } } } else if (this == PROPERTIES_PAIRS || this == PROPERTIES_XML) { Properties properties = new Properties(); if (this == PROPERTIES_PAIRS) properties.load(input); else if (this == PROPERTIES_XML) properties.loadFromXML(input); for (Object key : properties.keySet()) { Object value = properties.get(key); if (key instanceof String && value instanceof String) { KeyStroke keystroke = KeyStroke.getKeyStroke((String) key); if (keystroke == null) { StringBuilder message = new StringBuilder(); message .append("Unable to parse keystroke, see the getKeyStroke(String) method of "); message.append(KeyStroke.class.getName()); message.append(" for proper format"); throw new ParseException(message.toString(), 0); } else { output.put(keystroke, (String) value); } } else { if (key == null || value == null) { throw new ParseException("Unable to load null content", 0); } else { StringBuilder message = new StringBuilder(); message .append("Entry doesn't represent a keybinding: "); message.append(key.getClass().getName()); message.append(" -> "); message.append(value.getClass().getName()); message .append("\nMust match String -> String mapping where the first string represents a keystroke"); throw new ParseException(message.toString(), 0); } } } } input.close(); return output; } /** * Writes the persistent state of the bindings to an output stream. * * @param output stream where persistent state should be written * @param bindings keybindings to be saved * @throws IOException if unable to save bindings * @throws UnsupportedOperationException if any keys or values of the * binding are null */ public void save(OutputStream output, Map<KeyStroke, String> bindings) throws IOException { for (KeyStroke key : bindings.keySet()) { if (key == null || bindings.get(key) == null) { throw new UnsupportedOperationException( "Invalid binding: Shortcuts and actions cannot be null"); } } if (this == SERIAL_HASH || this == SERIAL_INPUT) { Object mapping; // Mapping to be serialized if (this == SERIAL_HASH) mapping = bindings; else { InputMap inputMap = new InputMap(); for (KeyStroke shortcut : bindings.keySet()) { inputMap.put(shortcut, bindings.get(shortcut)); } mapping = inputMap; } ObjectOutputStream objectOutput = new ObjectOutputStream(output); objectOutput.writeObject(mapping); objectOutput.flush(); objectOutput.close(); } else if (this == PROPERTIES_PAIRS || this == PROPERTIES_XML) { Properties properties = new Properties(); for (KeyStroke shortcut : bindings.keySet()) { properties.setProperty(shortcut.toString(), bindings .get(shortcut)); } if (this == PROPERTIES_PAIRS) properties.store(output, PROPERTIES_COMMENT); else properties.storeToXML(output, PROPERTIES_COMMENT); } } /** * Writes the persistent state of the bindings to a file. * * @param path absolute path to where bindings should be saved * @param bindings keybindings to be saved * @throws IOException if unable to save bindings * @throws UnsupportedOperationException if any keys or values of the * binding are null */ public void save(String path, Map<KeyStroke, String> bindings) throws IOException { FileOutputStream output = new FileOutputStream(path); try { save(output, bindings); output.flush(); output.close(); } catch (IOException exc) { output.flush(); output.close(); throw exc; } catch (UnsupportedOperationException exc) { output.flush(); output.close(); throw exc; } } /** * Provides the textual output of what this persistence format would save * given a set of bindings. This silently fails, returning null if unable to * generate output from bindings. * * @param bindings bindings for which to generate saved output * @return string reflecting what would be saved by this persistence format */ public String getOutput(Map<KeyStroke, String> bindings) { /*- * This utilizes a rather lengthy chain of redirection to generate output as a string: * PipedOutputStream -> * PipedInputStream -> * Scanner -> * StringBuilder -> * String */ PipedOutputStream pipeOut = new PipedOutputStream(); PipedInputStream pipeIn = new PipedInputStream(); Scanner scanner = new Scanner(pipeIn); try { pipeOut.connect(pipeIn); save(pipeOut, bindings); pipeOut.flush(); pipeOut.close(); StringBuilder builder = new StringBuilder(); if (scanner.hasNextLine()) builder.append(scanner.nextLine()); while (scanner.hasNextLine()) { builder.append("\n"); builder.append(scanner.nextLine()); } scanner.close(); pipeIn.close(); return builder.toString(); } catch (IOException exc) { return null; } catch (UnsupportedOperationException exc) { return null; } } @Override public String toString() { if (this == SERIAL_HASH) return "Serialized Hash Map"; else if (this == SERIAL_INPUT) return "Serialized Input Map"; else if (this == PROPERTIES_XML) return "Properties XML"; else return getReadableConstant(this.name()); } /** * Provides a more readable version of constant names. Spaces replace * underscores and this changes the input to lowercase except the first * letter of each word. For instance, "RARE_CARDS" would become * "Rare Cards". * * @param input string to be converted * @return reader friendly variant of constant name */ public static String getReadableConstant(String input) { char[] name = input.toCharArray(); boolean isStartOfWord = true; for (int i = 0; i < name.length; ++i) { char chr = name[i]; if (chr == '_') name[i] = ' '; else if (isStartOfWord) name[i] = Character.toUpperCase(chr); else name[i] = Character.toLowerCase(chr); isStartOfWord = chr == '_'; } return new String(name); } }
jitsi/jitsi
modules/service/keybindings/src/main/java/net/java/sip/communicator/service/keybindings/Persistence.java
214,018
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ /* * This file was imported from apache http client 3.1 library and modified * to work for the YaCy http server when htto client library use was migrated * to apache http components 4.0 * by Michael Christen, 20.09.2010 */ package net.yacy.server.http; import java.io.IOException; import java.io.InputStream; /** * Cuts the wrapped InputStream off after a specified number of bytes. * * <p>Implementation note: Choices abound. One approach would pass * through the {@link InputStream#mark} and {@link InputStream#reset} calls to * the underlying stream. That's tricky, though, because you then have to * start duplicating the work of keeping track of how much a reset rewinds. * Further, you have to watch out for the "readLimit", and since the semantics * for the readLimit leave room for differing implementations, you might get * into a lot of trouble.</p> * * <p>Alternatively, you could make this class extend {@link java.io.BufferedInputStream} * and then use the protected members of that class to avoid duplicated effort. * That solution has the side effect of adding yet another possible layer of * buffering.</p> * * <p>Then, there is the simple choice, which this takes - simply don't * support {@link InputStream#mark} and {@link InputStream#reset}. That choice * has the added benefit of keeping this class very simple.</p> * * @author Ortwin Glueck * @author Eric Johnson * @author <a href="mailto:[email protected]">Mike Bowler</a> * @since 2.0 */ public class ContentLengthInputStream extends InputStream { /** * The maximum number of bytes that can be read from the stream. Subsequent * read operations will return -1. */ private final long contentLength; /** The current position */ private long pos = 0; /** True if the stream is closed. */ private boolean closed = false; /** * Wrapped input stream that all calls are delegated to. */ private InputStream wrappedStream = null; /** * Creates a new length limited stream * * @param in The stream to wrap * @param contentLength The maximum number of bytes that can be read from * the stream. Subsequent read operations will return -1. * * @since 3.0 */ public ContentLengthInputStream(InputStream in, long contentLength) { super(); this.wrappedStream = in; this.contentLength = contentLength; } /** * <p>Reads until the end of the known length of content.</p> * * <p>Does not close the underlying socket input, but instead leaves it * primed to parse the next response.</p> * @throws IOException If an IO problem occurs. */ @Override public synchronized void close() throws IOException { if (!this.closed) { try { ChunkedInputStream.exhaustInputStream(this); } finally { // close after above so that we don't throw an exception trying // to read after closed! this.closed = true; } } } /** * Read the next byte from the stream * @return The next byte or -1 if the end of stream has been reached. * @throws IOException If an IO problem occurs * @see java.io.InputStream#read() */ @Override public int read() throws IOException { if (this.closed) { throw new IOException("Attempted read from closed stream."); } if (this.pos >= this.contentLength) { return -1; } this.pos++; return this.wrappedStream.read(); } /** * Does standard {@link InputStream#read(byte[], int, int)} behavior, but * also notifies the watcher when the contents have been consumed. * * @param b The byte array to fill. * @param off Start filling at this position. * @param len The number of bytes to attempt to read. * @return The number of bytes read, or -1 if the end of content has been * reached. * * @throws java.io.IOException Should an error occur on the wrapped stream. */ @Override public int read (byte[] b, int off, int len) throws java.io.IOException { if (this.closed) { throw new IOException("Attempted read from closed stream."); } if (this.pos >= this.contentLength) { return -1; } if (this.pos + len > this.contentLength) { len = (int) (this.contentLength - this.pos); } int count = this.wrappedStream.read(b, off, len); this.pos += count; return count; } /** * Read more bytes from the stream. * @param b The byte array to put the new data in. * @return The number of bytes read into the buffer. * @throws IOException If an IO problem occurs * @see java.io.InputStream#read(byte[]) */ @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } /** * Skips and discards a number of bytes from the input stream. * @param n The number of bytes to skip. * @return The actual number of bytes skipped. <= 0 if no bytes * are skipped. * @throws IOException If an error occurs while skipping bytes. * @see InputStream#skip(long) */ @Override public long skip(long n) throws IOException { // make sure we don't skip more bytes than are // still available long length = Math.min(n, this.contentLength - this.pos); // skip and keep track of the bytes actually skipped length = this.wrappedStream.skip(length); // only add the skipped bytes to the current position // if bytes were actually skipped if (length > 0) { this.pos += length; } return length; } @Override public int available() throws IOException { if (this.closed) { return 0; } int avail = this.wrappedStream.available(); if (this.pos + avail > this.contentLength ) { avail = (int)(this.contentLength - this.pos); } return avail; } }
yacy/yacy_search_server
source/net/yacy/server/http/ContentLengthInputStream.java
214,019
package com.baeldung; import java.util.List; /** * Created by johnson on 3/9/17. */ public interface LedgerServiceInterface { List<String> getEntries(int count); }
eugenp/tutorials
persistence-modules/redis/src/main/java/com/baeldung/LedgerServiceInterface.java
214,020
package android.content.pm; import android.os.Parcel; import android.os.Parcelable; import java.security.PublicKey; /** * @author johnsonlee */ public class VerifierInfo implements Parcelable{ public static final Parcelable.Creator<VerifierInfo> CREATOR = new Parcelable.Creator<VerifierInfo>() { public VerifierInfo createFromParcel(final Parcel source) { return new VerifierInfo(source); } public VerifierInfo[] newArray(final int size) { return new VerifierInfo[size]; } }; public VerifierInfo(final String packageName, final PublicKey publicKey) { throw new RuntimeException("Stub!"); } private VerifierInfo(final Parcel source) { throw new RuntimeException("Stub!"); } @Override public int describeContents() { throw new RuntimeException("Stub!"); } @Override public void writeToParcel(final Parcel dest, final int flags) { throw new RuntimeException("Stub!"); } }
didi/VirtualAPK
AndroidStub/src/main/java/android/content/pm/VerifierInfo.java
214,023
/******************************************************************************* * Copyright (c) 1997, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ // defect 400645 "Batchcompiler needs to get webcon custom props" 2004/10/25 Scott Johnson // 395182.2 70FVT: make servlet 2.3 compatible with JSP 2.1 for migration 2007/02/07 Scott Johnson package com.ibm.ws.jsp.configuration; import java.util.List; import java.util.Map; import java.util.Properties; import com.ibm.ws.jsp.JspOptions; /** * @author Scott Johnson * * API for retrieving JSP configuration elements from both web.xml and the extensions document */ public interface JspXmlExtConfig { public Map getTagLibMap(); public List getJspPropertyGroups(); public boolean isServlet24(); public boolean isServlet24_or_higher(); public JspOptions getJspOptions(); public List getJspFileExtensions(); public boolean containsServletClassName(String servletClassName); //defect 400645 public void setWebContainerProperties(Properties webConProperties); public Properties getWebContainerProperties(); //defect 400645 //only used during runtime when JCDI will use this to determine whether to wrap the ExpressionFactory public void setJCDIEnabledForRuntimeCheck(boolean b); public boolean isJCDIEnabledForRuntimeCheck(); }
tjwatson/open-liberty
dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/configuration/JspXmlExtConfig.java
214,024
/** * The MIT License * ------------------------------------------------------------- * Copyright (c) 2008, Rob Ellis, Brock Whitten, Brian Leroux, Joe Bowser, Dave Johnson, Nitobi * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.nitobi.phonegap.io; /** * Indicates the need to execute some additional code once the requested * task has finished. * * @author Jose Noheda * */ public interface Callback { /** * Method to execute once the asynchronous process has finished. * * @param input anything */ public void execute(final Object input); }
claymodel/phonegap
blackberry/framework/src/com/nitobi/phonegap/io/Callback.java
214,026
/* * * This file is part of the iText (R) project. * Copyright (c) 2014-2015 iText Group NV * Authors: Bruno Lowagie, Paulo Soares, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: * http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, * a covered work must retain the producer line in every PDF that is created * or manipulated using iText. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the iText software without * disclosing the source code of your own applications. * These activities include: offering paid services to customers as an ASP, * serving PDFs on the fly in a web application, shipping iText with a closed * source product. * * For more information, please contact iText Software Corp. at this * address: [email protected] * * * This class is based on the C# open source freeware library Clipper: * http://www.angusj.com/delphi/clipper.php * The original classes were distributed under the Boost Software License: * * Freeware for both open source and commercial applications * Copyright 2010-2014 Angus Johnson * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.itextpdf.text.pdf.parser.clipper; import com.itextpdf.text.pdf.parser.clipper.Path.Join; import com.itextpdf.text.pdf.parser.clipper.Path.OutRec; import com.itextpdf.text.pdf.parser.clipper.Point.LongPoint; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.logging.Logger; public class DefaultClipper extends ClipperBase { private class IntersectNode { Edge edge1; Edge Edge2; private LongPoint pt; public LongPoint getPt() { return pt; } public void setPt( LongPoint pt ) { this.pt = pt; } }; private static void getHorzDirection( Edge HorzEdge, Direction[] Dir, long[] Left, long[] Right ) { if (HorzEdge.getBot().getX() < HorzEdge.getTop().getX()) { Left[0] = HorzEdge.getBot().getX(); Right[0] = HorzEdge.getTop().getX(); Dir[0] = Direction.LEFT_TO_RIGHT; } else { Left[0] = HorzEdge.getTop().getX(); Right[0] = HorzEdge.getBot().getX(); Dir[0] = Direction.RIGHT_TO_LEFT; } } private static boolean getOverlap( long a1, long a2, long b1, long b2, long[] Left, long[] Right ) { if (a1 < a2) { if (b1 < b2) { Left[0] = Math.max( a1, b1 ); Right[0] = Math.min( a2, b2 ); } else { Left[0] = Math.max( a1, b2 ); Right[0] = Math.min( a2, b1 ); } } else { if (b1 < b2) { Left[0] = Math.max( a2, b1 ); Right[0] = Math.min( a1, b2 ); } else { Left[0] = Math.max( a2, b2 ); Right[0] = Math.min( a1, b1 ); } } return Left[0] < Right[0]; } private static boolean isParam1RightOfParam2( OutRec outRec1, OutRec outRec2 ) { do { outRec1 = outRec1.firstLeft; if (outRec1 == outRec2) { return true; } } while (outRec1 != null); return false; } //See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos //http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf private static int isPointInPolygon( LongPoint pt, Path.OutPt op ) { //returns 0 if false, +1 if true, -1 if pt ON polygon boundary int result = 0; final Path.OutPt startOp = op; final long ptx = pt.getX(), pty = pt.getY(); long poly0x = op.getPt().getX(), poly0y = op.getPt().getY(); do { op = op.next; final long poly1x = op.getPt().getX(), poly1y = op.getPt().getY(); if (poly1y == pty) { if (poly1x == ptx || poly0y == pty && poly1x > ptx == poly0x < ptx) { return -1; } } if (poly0y < pty != poly1y < pty) { if (poly0x >= ptx) { if (poly1x > ptx) { result = 1 - result; } else { final double d = (double) (poly0x - ptx) * (poly1y - pty) - (double) (poly1x - ptx) * (poly0y - pty); if (d == 0) { return -1; } if (d > 0 == poly1y > poly0y) { result = 1 - result; } } } else { if (poly1x > ptx) { final double d = (double) (poly0x - ptx) * (poly1y - pty) - (double) (poly1x - ptx) * (poly0y - pty); if (d == 0) { return -1; } if (d > 0 == poly1y > poly0y) { result = 1 - result; } } } } poly0x = poly1x; poly0y = poly1y; } while (startOp != op); return result; } //------------------------------------------------------------------------------ private static boolean joinHorz( Path.OutPt op1, Path.OutPt op1b, Path.OutPt op2, Path.OutPt op2b, LongPoint Pt, boolean DiscardLeft ) { final Direction Dir1 = op1.getPt().getX() > op1b.getPt().getX() ? Direction.RIGHT_TO_LEFT : Direction.LEFT_TO_RIGHT; final Direction Dir2 = op2.getPt().getX() > op2b.getPt().getX() ? Direction.RIGHT_TO_LEFT : Direction.LEFT_TO_RIGHT; if (Dir1 == Dir2) { return false; } //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we //want Op1b to be on the Right. (And likewise with Op2 and Op2b.) //So, to facilitate this while inserting Op1b and Op2b ... //when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b, //otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.) if (Dir1 == Direction.LEFT_TO_RIGHT) { while (op1.next.getPt().getX() <= Pt.getX() && op1.next.getPt().getX() >= op1.getPt().getX() && op1.next.getPt().getY() == Pt.getY()) { op1 = op1.next; } if (DiscardLeft && op1.getPt().getX() != Pt.getX()) { op1 = op1.next; } op1b = op1.duplicate( !DiscardLeft ); if (!op1b.getPt().equals( Pt )) { op1 = op1b; op1.setPt( Pt ); op1b = op1.duplicate( !DiscardLeft ); } } else { while (op1.next.getPt().getX() >= Pt.getX() && op1.next.getPt().getX() <= op1.getPt().getX() && op1.next.getPt().getY() == Pt.getY()) { op1 = op1.next; } if (!DiscardLeft && op1.getPt().getX() != Pt.getX()) { op1 = op1.next; } op1b = op1.duplicate( DiscardLeft ); if (!op1b.getPt().equals( Pt )) { op1 = op1b; op1.setPt( Pt ); op1b = op1.duplicate( DiscardLeft ); } } if (Dir2 == Direction.LEFT_TO_RIGHT) { while (op2.next.getPt().getX() <= Pt.getX() && op2.next.getPt().getX() >= op2.getPt().getX() && op2.next.getPt().getY() == Pt.getY()) { op2 = op2.next; } if (DiscardLeft && op2.getPt().getX() != Pt.getX()) { op2 = op2.next; } op2b = op2.duplicate( !DiscardLeft ); if (!op2b.getPt().equals( Pt )) { op2 = op2b; op2.setPt( Pt ); op2b = op2.duplicate( !DiscardLeft ); } ; } else { while (op2.next.getPt().getX() >= Pt.getX() && op2.next.getPt().getX() <= op2.getPt().getX() && op2.next.getPt().getY() == Pt.getY()) { op2 = op2.next; } if (!DiscardLeft && op2.getPt().getX() != Pt.getX()) { op2 = op2.next; } op2b = op2.duplicate( DiscardLeft ); if (!op2b.getPt().equals( Pt )) { op2 = op2b; op2.setPt( Pt ); op2b = op2.duplicate( DiscardLeft ); } ; } ; if (Dir1 == Direction.LEFT_TO_RIGHT == DiscardLeft) { op1.prev = op2; op2.next = op1; op1b.next = op2b; op2b.prev = op1b; } else { op1.next = op2; op2.prev = op1; op1b.prev = op2b; op2b.next = op1b; } return true; } private boolean joinPoints( Join j, OutRec outRec1, OutRec outRec2 ) { Path.OutPt op1 = j.outPt1, op1b; Path.OutPt op2 = j.outPt2, op2b; //There are 3 kinds of joins for output polygons ... //1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are a vertices anywhere //along (horizontal) collinear edges (& Join.OffPt is on the same horizontal). //2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same //location at the Bottom of the overlapping segment (& Join.OffPt is above). //3. StrictlySimple joins where edges touch but are not collinear and where //Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point. final boolean isHorizontal = j.outPt1.getPt().getY() == j.getOffPt().getY(); if (isHorizontal && j.getOffPt().equals( j.outPt1.getPt() ) && j.getOffPt().equals( j.outPt2.getPt() )) { //Strictly Simple join ... if (outRec1 != outRec2) { return false; } op1b = j.outPt1.next; while (op1b != op1 && op1b.getPt().equals( j.getOffPt() )) { op1b = op1b.next; } final boolean reverse1 = op1b.getPt().getY() > j.getOffPt().getY(); op2b = j.outPt2.next; while (op2b != op2 && op2b.getPt().equals( j.getOffPt() )) { op2b = op2b.next; } final boolean reverse2 = op2b.getPt().getY() > j.getOffPt().getY(); if (reverse1 == reverse2) { return false; } if (reverse1) { op1b = op1.duplicate( false ); op2b = op2.duplicate( true ); op1.prev = op2; op2.next = op1; op1b.next = op2b; op2b.prev = op1b; j.outPt1 = op1; j.outPt2 = op1b; return true; } else { op1b = op1.duplicate( true ); op2b = op2.duplicate( false ); op1.next = op2; op2.prev = op1; op1b.prev = op2b; op2b.next = op1b; j.outPt1 = op1; j.outPt2 = op1b; return true; } } else if (isHorizontal) { //treat horizontal joins differently to non-horizontal joins since with //them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt //may be anywhere along the horizontal edge. op1b = op1; while (op1.prev.getPt().getY() == op1.getPt().getY() && op1.prev != op1b && op1.prev != op2) { op1 = op1.prev; } while (op1b.next.getPt().getY() == op1b.getPt().getY() && op1b.next != op1 && op1b.next != op2) { op1b = op1b.next; } if (op1b.next == op1 || op1b.next == op2) { return false; } //a flat 'polygon' op2b = op2; while (op2.prev.getPt().getY() == op2.getPt().getY() && op2.prev != op2b && op2.prev != op1b) { op2 = op2.prev; } while (op2b.next.getPt().getY() == op2b.getPt().getY() && op2b.next != op2 && op2b.next != op1) { op2b = op2b.next; } if (op2b.next == op2 || op2b.next == op1) { return false; } //a flat 'polygon' final long[] LeftV = new long[1], RightV = new long[1]; //Op1 -. Op1b & Op2 -. Op2b are the extremites of the horizontal edges if (!getOverlap( op1.getPt().getX(), op1b.getPt().getX(), op2.getPt().getX(), op2b.getPt().getX(), LeftV, RightV )) { return false; } final long Left = LeftV[0]; final long Right = RightV[0]; //DiscardLeftSide: when overlapping edges are joined, a spike will created //which needs to be cleaned up. However, we don't want Op1 or Op2 caught up //on the discard Side as either may still be needed for other joins ... LongPoint Pt; boolean DiscardLeftSide; if (op1.getPt().getX() >= Left && op1.getPt().getX() <= Right) { Pt = new LongPoint( op1.getPt() ); DiscardLeftSide = op1.getPt().getX() > op1b.getPt().getX(); } else if (op2.getPt().getX() >= Left && op2.getPt().getX() <= Right) { Pt = new LongPoint( op2.getPt() ); DiscardLeftSide = op2.getPt().getX() > op2b.getPt().getX(); } else if (op1b.getPt().getX() >= Left && op1b.getPt().getX() <= Right) { Pt = new LongPoint( op1b.getPt() ); DiscardLeftSide = op1b.getPt().getX() > op1.getPt().getX(); } else { Pt = new LongPoint( op2b.getPt() ); DiscardLeftSide = op2b.getPt().getX() > op2.getPt().getX(); } j.outPt1 = op1; j.outPt2 = op2; return joinHorz( op1, op1b, op2, op2b, Pt, DiscardLeftSide ); } else { //nb: For non-horizontal joins ... // 1. Jr.OutPt1.getPt().getY() == Jr.OutPt2.getPt().getY() // 2. Jr.OutPt1.Pt > Jr.OffPt.getY() //make sure the polygons are correctly oriented ... op1b = op1.next; while (op1b.getPt().equals( op1.getPt() ) && op1b != op1) { op1b = op1b.next; } final boolean Reverse1 = op1b.getPt().getY() > op1.getPt().getY() || !Point.slopesEqual( op1.getPt(), op1b.getPt(), j.getOffPt(), useFullRange ); if (Reverse1) { op1b = op1.prev; while (op1b.getPt().equals( op1.getPt() ) && op1b != op1) { op1b = op1b.prev; } if (op1b.getPt().getY() > op1.getPt().getY() || !Point.slopesEqual( op1.getPt(), op1b.getPt(), j.getOffPt(), useFullRange )) { return false; } } ; op2b = op2.next; while (op2b.getPt().equals( op2.getPt() ) && op2b != op2) { op2b = op2b.next; } final boolean Reverse2 = op2b.getPt().getY() > op2.getPt().getY() || !Point.slopesEqual( op2.getPt(), op2b.getPt(), j.getOffPt(), useFullRange ); if (Reverse2) { op2b = op2.prev; while (op2b.getPt().equals( op2.getPt() ) && op2b != op2) { op2b = op2b.prev; } if (op2b.getPt().getY() > op2.getPt().getY() || !Point.slopesEqual( op2.getPt(), op2b.getPt(), j.getOffPt(), useFullRange )) { return false; } } if (op1b == op1 || op2b == op2 || op1b == op2b || outRec1 == outRec2 && Reverse1 == Reverse2) { return false; } if (Reverse1) { op1b = op1.duplicate( false ); op2b = op2.duplicate( true ); op1.prev = op2; op2.next = op1; op1b.next = op2b; op2b.prev = op1b; j.outPt1 = op1; j.outPt2 = op1b; return true; } else { op1b = op1.duplicate( true ); op2b = op2.duplicate( false ); op1.next = op2; op2.prev = op1; op1b.prev = op2b; op2b.next = op1b; j.outPt1 = op1; j.outPt2 = op1b; return true; } } } private static Paths minkowski( Path pattern, Path path, boolean IsSum, boolean IsClosed ) { final int delta = IsClosed ? 1 : 0; final int polyCnt = pattern.size(); final int pathCnt = path.size(); final Paths result = new Paths( pathCnt ); if (IsSum) { for (int i = 0; i < pathCnt; i++) { final Path p = new Path( polyCnt ); for (final LongPoint ip : pattern) { p.add( new LongPoint( path.get( i ).getX() + ip.getX(), path.get( i ).getY() + ip.getY(), 0 ) ); } result.add( p ); } } else { for (int i = 0; i < pathCnt; i++) { final Path p = new Path( polyCnt ); for (final LongPoint ip : pattern) { p.add( new LongPoint( path.get( i ).getX() - ip.getX(), path.get( i ).getY() - ip.getY(), 0 ) ); } result.add( p ); } } final Paths quads = new Paths( (pathCnt + delta) * (polyCnt + 1) ); for (int i = 0; i < pathCnt - 1 + delta; i++) { for (int j = 0; j < polyCnt; j++) { final Path quad = new Path( 4 ); quad.add( result.get( i % pathCnt ).get( j % polyCnt ) ); quad.add( result.get( (i + 1) % pathCnt ).get( j % polyCnt ) ); quad.add( result.get( (i + 1) % pathCnt ).get( (j + 1) % polyCnt ) ); quad.add( result.get( i % pathCnt ).get( (j + 1) % polyCnt ) ); if (!quad.orientation()) { Collections.reverse( quad ); } quads.add( quad ); } } return quads; } public static Paths minkowskiDiff( Path poly1, Path poly2 ) { final Paths paths = minkowski( poly1, poly2, false, true ); final DefaultClipper c = new DefaultClipper(); c.addPaths( paths, PolyType.SUBJECT, true ); c.execute( ClipType.UNION, paths, PolyFillType.NON_ZERO, PolyFillType.NON_ZERO ); return paths; } public static Paths minkowskiSum( Path pattern, Path path, boolean pathIsClosed ) { final Paths paths = minkowski( pattern, path, true, pathIsClosed ); final DefaultClipper c = new DefaultClipper(); c.addPaths( paths, PolyType.SUBJECT, true ); c.execute( ClipType.UNION, paths, PolyFillType.NON_ZERO, PolyFillType.NON_ZERO ); return paths; } public static Paths minkowskiSum( Path pattern, Paths paths, boolean pathIsClosed ) { final Paths solution = new Paths(); final DefaultClipper c = new DefaultClipper(); for (int i = 0; i < paths.size(); ++i) { final Paths tmp = minkowski( pattern, paths.get( i ), true, pathIsClosed ); c.addPaths( tmp, PolyType.SUBJECT, true ); if (pathIsClosed) { final Path path = paths.get( i ).TranslatePath( pattern.get( 0 ) ); c.addPath( path, PolyType.CLIP, true ); } } c.execute( ClipType.UNION, solution, PolyFillType.NON_ZERO, PolyFillType.NON_ZERO ); return solution; } private static boolean poly2ContainsPoly1( Path.OutPt outPt1, Path.OutPt outPt2 ) { Path.OutPt op = outPt1; do { //nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon final int res = isPointInPolygon( op.getPt(), outPt2 ); if (res >= 0) { return res > 0; } op = op.next; } while (op != outPt1); return true; } //------------------------------------------------------------------------------ // SimplifyPolygon functions ... // Convert self-intersecting polygons into simple polygons //------------------------------------------------------------------------------ public static Paths simplifyPolygon( Path poly ) { return simplifyPolygon( poly, PolyFillType.EVEN_ODD ); } public static Paths simplifyPolygon( Path poly, PolyFillType fillType ) { final Paths result = new Paths(); final DefaultClipper c = new DefaultClipper( STRICTLY_SIMPLE ); c.addPath( poly, PolyType.SUBJECT, true ); c.execute( ClipType.UNION, result, fillType, fillType ); return result; } public static Paths simplifyPolygons( Paths polys ) { return simplifyPolygons( polys, PolyFillType.EVEN_ODD ); } public static Paths simplifyPolygons( Paths polys, PolyFillType fillType ) { final Paths result = new Paths(); final DefaultClipper c = new DefaultClipper( STRICTLY_SIMPLE ); c.addPaths( polys, PolyType.SUBJECT, true ); c.execute( ClipType.UNION, result, fillType, fillType ); return result; } protected final List<OutRec> polyOuts; private ClipType clipType; private Scanbeam scanbeam; private Path.Maxima maxima; private Edge activeEdges; private Edge sortedEdges; private final List<IntersectNode> intersectList; private final Comparator<IntersectNode> intersectNodeComparer; private PolyFillType clipFillType; //------------------------------------------------------------------------------ private PolyFillType subjFillType; //------------------------------------------------------------------------------ private final List<Join> joins; //------------------------------------------------------------------------------ private final List<Join> ghostJoins; private boolean usingPolyTree; public ZFillCallback zFillFunction; //------------------------------------------------------------------------------ private final boolean reverseSolution; //------------------------------------------------------------------------------ private final boolean strictlySimple; private final static Logger LOGGER = Logger.getLogger( DefaultClipper.class.getName() ); public DefaultClipper() { this( 0 ); } public DefaultClipper( int InitOptions ) //constructor { super( (PRESERVE_COLINEAR & InitOptions) != 0 ); scanbeam = null; maxima = null; activeEdges = null; sortedEdges = null; intersectList = new ArrayList<IntersectNode>(); intersectNodeComparer = new Comparator<IntersectNode>() { public int compare(IntersectNode o1, IntersectNode o2) { final long i = o2.getPt().getY() - o1.getPt().getY(); if (i > 0) { return 1; } else if (i < 0) { return -1; } else { return 0; } } }; usingPolyTree = false; polyOuts = new ArrayList<OutRec>(); joins = new ArrayList<Join>(); ghostJoins = new ArrayList<Join>(); reverseSolution = (REVERSE_SOLUTION & InitOptions) != 0; strictlySimple = (STRICTLY_SIMPLE & InitOptions) != 0; zFillFunction = null; } private void insertScanbeam(long Y) { //single-linked list: sorted descending, ignoring dups. if (scanbeam == null) { scanbeam = new Scanbeam(); scanbeam.next = null; scanbeam.y = Y; } else if (Y > scanbeam.y) { Scanbeam newSb = new Scanbeam(); newSb.y = Y; newSb.next = scanbeam; scanbeam = newSb; } else { Scanbeam sb2 = scanbeam; while (sb2.next != null && (Y <= sb2.next.y)) sb2 = sb2.next; if (Y == sb2.y) return; //ie ignores duplicates Scanbeam newSb = new Scanbeam(); newSb.y = Y; newSb.next = sb2.next; sb2.next = newSb; } } //------------------------------------------------------------------------------ private void InsertMaxima(long X) { //double-linked list: sorted ascending, ignoring dups. Path.Maxima newMax = new Path.Maxima(); newMax.X = X; if (maxima == null) { maxima = newMax; maxima.Next = null; maxima.Prev = null; } else if (X < maxima.X) { newMax.Next = maxima; newMax.Prev = null; maxima = newMax; } else { Path.Maxima m = maxima; while (m.Next != null && (X >= m.Next.X)) m = m.Next; if (X == m.X) return; //ie ignores duplicates (& CG to clean up newMax) //insert newMax between m and m.Next ... newMax.Next = m.Next; newMax.Prev = m; if (m.Next != null) m.Next.Prev = newMax; m.Next = newMax; } } //------------------------------------------------------------------------------ private void addEdgeToSEL( Edge edge ) { LOGGER.entering( DefaultClipper.class.getName(), "addEdgeToSEL" ); //SEL pointers in PEdge are reused to build a list of horizontal edges. //However, we don't need to worry about order with horizontal edge processing. if (sortedEdges == null) { sortedEdges = edge; edge.prevInSEL = null; edge.nextInSEL = null; } else { edge.nextInSEL = sortedEdges; edge.prevInSEL = null; sortedEdges.prevInSEL = edge; sortedEdges = edge; } } private void addGhostJoin( Path.OutPt Op, LongPoint OffPt ) { final Join j = new Join(); j.outPt1 = Op; j.setOffPt( OffPt ); ghostJoins.add( j ); } //------------------------------------------------------------------------------ private void addJoin( Path.OutPt Op1, Path.OutPt Op2, LongPoint OffPt ) { LOGGER.entering(DefaultClipper.class.getName(), "addJoin"); final Join j = new Join(); j.outPt1 = Op1; j.outPt2 = Op2; j.setOffPt( OffPt ); joins.add( j ); } //------------------------------------------------------------------------------ private void addLocalMaxPoly( Edge e1, Edge e2, LongPoint pt ) { addOutPt(e1, pt); if (e2.windDelta == 0) { addOutPt( e2, pt ); } if (e1.outIdx == e2.outIdx) { e1.outIdx = Edge.UNASSIGNED; e2.outIdx = Edge.UNASSIGNED; } else if (e1.outIdx < e2.outIdx) { appendPolygon( e1, e2 ); } else { appendPolygon( e2, e1 ); } } //------------------------------------------------------------------------------ private Path.OutPt addLocalMinPoly( Edge e1, Edge e2, LongPoint pt ) { LOGGER.entering( DefaultClipper.class.getName(), "addLocalMinPoly" ); Path.OutPt result; Edge e, prevE; if (e2.isHorizontal() || e1.deltaX > e2.deltaX) { result = addOutPt( e1, pt ); e2.outIdx = e1.outIdx; e1.side = Edge.Side.LEFT; e2.side = Edge.Side.RIGHT; e = e1; if (e.prevInAEL == e2) { prevE = e2.prevInAEL; } else { prevE = e.prevInAEL; } } else { result = addOutPt( e2, pt ); e1.outIdx = e2.outIdx; e1.side = Edge.Side.RIGHT; e2.side = Edge.Side.LEFT; e = e2; if (e.prevInAEL == e1) { prevE = e1.prevInAEL; } else { prevE = e.prevInAEL; } } if (prevE != null && prevE.outIdx >= 0 && Edge.topX( prevE, pt.getY() ) == Edge.topX( e, pt.getY() ) && Edge.slopesEqual( e, prevE, useFullRange ) && e.windDelta != 0 && prevE.windDelta != 0) { final Path.OutPt outPt = addOutPt( prevE, pt ); addJoin( result, outPt, e.getTop() ); } return result; } private Path.OutPt addOutPt( Edge e, LongPoint pt ) { LOGGER.entering( DefaultClipper.class.getName(), "addOutPt" ); if (e.outIdx < 0) { OutRec outRec = createOutRec(); outRec.isOpen = (e.windDelta == 0); Path.OutPt newOp = new Path.OutPt(); outRec.pts = newOp; newOp.idx = outRec.Idx; newOp.pt = pt; newOp.next = newOp; newOp.prev = newOp; if (!outRec.isOpen) setHoleState(e, outRec); e.outIdx = outRec.Idx; //nb: do this after SetZ ! return newOp; } else { final OutRec outRec = polyOuts.get( e.outIdx ); //OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most' final Path.OutPt op = outRec.getPoints(); boolean ToFront = (e.side == Edge.Side.LEFT); LOGGER.finest( "op=" + op.getPointCount() ); LOGGER.finest( ToFront + " " + pt + " " + op.getPt() ); if (ToFront && pt.equals( op.getPt() )) { return op; } else if (!ToFront && pt.equals( op.prev.getPt() )) { return op.prev; } final Path.OutPt newOp = new Path.OutPt(); newOp.idx = outRec.Idx; newOp.setPt( new LongPoint( pt ) ); newOp.next = op; newOp.prev = op.prev; newOp.prev.next = newOp; op.prev = newOp; if (ToFront) { outRec.setPoints( newOp ); } return newOp; } } private Path.OutPt GetLastOutPt(Edge e) { OutRec outRec = polyOuts.get(e.outIdx); if (e.side == Edge.Side.LEFT) return outRec.pts; else return outRec.pts.prev; } //------------------------------------------------------------------------------ private void appendPolygon( Edge e1, Edge e2 ) { LOGGER.entering( DefaultClipper.class.getName(), "appendPolygon" ); //get the start and ends of both output polygons ... final OutRec outRec1 = polyOuts.get( e1.outIdx ); final OutRec outRec2 = polyOuts.get( e2.outIdx ); LOGGER.finest( "" + e1.outIdx ); LOGGER.finest( "" + e2.outIdx ); OutRec holeStateRec; if (isParam1RightOfParam2( outRec1, outRec2 )) { holeStateRec = outRec2; } else if (isParam1RightOfParam2( outRec2, outRec1 )) { holeStateRec = outRec1; } else { holeStateRec = Path.OutPt.getLowerMostRec( outRec1, outRec2 ); } final Path.OutPt p1_lft = outRec1.getPoints(); final Path.OutPt p1_rt = p1_lft.prev; final Path.OutPt p2_lft = outRec2.getPoints(); final Path.OutPt p2_rt = p2_lft.prev; LOGGER.finest( "p1_lft.getPointCount() = " + p1_lft.getPointCount() ); LOGGER.finest( "p1_rt.getPointCount() = " + p1_rt.getPointCount() ); LOGGER.finest( "p2_lft.getPointCount() = " + p2_lft.getPointCount() ); LOGGER.finest( "p2_rt.getPointCount() = " + p2_rt.getPointCount() ); Edge.Side side; //join e2 poly onto e1 poly and delete pointers to e2 ... if (e1.side == Edge.Side.LEFT) { if (e2.side == Edge.Side.LEFT) { //z y x a b c p2_lft.reversePolyPtLinks(); p2_lft.next = p1_lft; p1_lft.prev = p2_lft; p1_rt.next = p2_rt; p2_rt.prev = p1_rt; outRec1.setPoints( p2_rt ); } else { //x y z a b c p2_rt.next = p1_lft; p1_lft.prev = p2_rt; p2_lft.prev = p1_rt; p1_rt.next = p2_lft; outRec1.setPoints( p2_lft ); } side = Edge.Side.LEFT; } else { if (e2.side == Edge.Side.RIGHT) { //a b c z y x p2_lft.reversePolyPtLinks(); p1_rt.next = p2_rt; p2_rt.prev = p1_rt; p2_lft.next = p1_lft; p1_lft.prev = p2_lft; } else { //a b c x y z p1_rt.next = p2_lft; p2_lft.prev = p1_rt; p1_lft.prev = p2_rt; p2_rt.next = p1_lft; } side = Edge.Side.RIGHT; } outRec1.bottomPt = null; if (holeStateRec.equals( outRec2 )) { if (outRec2.firstLeft != outRec1) { outRec1.firstLeft = outRec2.firstLeft; } outRec1.isHole = outRec2.isHole; } outRec2.setPoints( null ); outRec2.bottomPt = null; outRec2.firstLeft = outRec1; final int OKIdx = e1.outIdx; final int ObsoleteIdx = e2.outIdx; e1.outIdx = Edge.UNASSIGNED; //nb: safe because we only get here via AddLocalMaxPoly e2.outIdx = Edge.UNASSIGNED; Edge e = activeEdges; while (e != null) { if (e.outIdx == ObsoleteIdx) { e.outIdx = OKIdx; e.side = side; break; } e = e.nextInAEL; } outRec2.Idx = outRec1.Idx; } //------------------------------------------------------------------------------ private void buildIntersectList( long topY ) { if (activeEdges == null) { return; } //prepare for sorting ... Edge e = activeEdges; sortedEdges = e; while (e != null) { e.prevInSEL = e.prevInAEL; e.nextInSEL = e.nextInAEL; e.getCurrent().setX( Edge.topX( e, topY ) ); e = e.nextInAEL; } //bubblesort ... boolean isModified = true; while (isModified && sortedEdges != null) { isModified = false; e = sortedEdges; while (e.nextInSEL != null) { final Edge eNext = e.nextInSEL; final LongPoint[] pt = new LongPoint[1]; if (e.getCurrent().getX() > eNext.getCurrent().getX()) { intersectPoint( e, eNext, pt ); final IntersectNode newNode = new IntersectNode(); newNode.edge1 = e; newNode.Edge2 = eNext; newNode.setPt( pt[0] ); intersectList.add( newNode ); swapPositionsInSEL( e, eNext ); isModified = true; } else { e = eNext; } } if (e.prevInSEL != null) { e.prevInSEL.nextInSEL = null; } else { break; } } sortedEdges = null; } //------------------------------------------------------------------------------ private void buildResult( Paths polyg ) { polyg.clear(); for (int i = 0; i < polyOuts.size(); i++) { final OutRec outRec = polyOuts.get( i ); if (outRec.getPoints() == null) { continue; } Path.OutPt p = outRec.getPoints().prev; final int cnt = p.getPointCount(); LOGGER.finest( "cnt = " + cnt ); if (cnt < 2) { continue; } final Path pg = new Path( cnt ); for (int j = 0; j < cnt; j++) { pg.add( p.getPt() ); p = p.prev; } polyg.add( pg ); } } private void buildResult2( PolyTree polytree ) { polytree.Clear(); //add each output polygon/contour to polytree ... for (int i = 0; i < polyOuts.size(); i++) { final OutRec outRec = polyOuts.get( i ); final int cnt = outRec.getPoints() != null ? outRec.getPoints().getPointCount() : 0; if (outRec.isOpen && cnt < 2 || !outRec.isOpen && cnt < 3) { continue; } outRec.fixHoleLinkage(); final PolyNode pn = new PolyNode(); polytree.getAllPolys().add( pn ); outRec.polyNode = pn; Path.OutPt op = outRec.getPoints().prev; for (int j = 0; j < cnt; j++) { pn.getPolygon().add( op.getPt() ); op = op.prev; } } //fixup PolyNode links etc ... for (int i = 0; i < polyOuts.size(); i++) { final OutRec outRec = polyOuts.get( i ); if (outRec.polyNode == null) { continue; } else if (outRec.isOpen) { outRec.polyNode.setOpen( true ); polytree.addChild( outRec.polyNode ); } else if (outRec.firstLeft != null && outRec.firstLeft.polyNode != null) { outRec.firstLeft.polyNode.addChild( outRec.polyNode ); } else { polytree.addChild( outRec.polyNode ); } } } private void copyAELToSEL() { Edge e = activeEdges; sortedEdges = e; while (e != null) { e.prevInSEL = e.prevInAEL; e.nextInSEL = e.nextInAEL; e = e.nextInAEL; } } private OutRec createOutRec() { final OutRec result = new OutRec(); result.Idx = Edge.UNASSIGNED; result.isHole = false; result.isOpen = false; result.firstLeft = null; result.setPoints( null ); result.bottomPt = null; result.polyNode = null; polyOuts.add( result ); result.Idx = polyOuts.size() - 1; return result; } private void deleteFromAEL( Edge e ) { LOGGER.entering( DefaultClipper.class.getName(), "deleteFromAEL" ); final Edge AelPrev = e.prevInAEL; final Edge AelNext = e.nextInAEL; if (AelPrev == null && AelNext == null && e != activeEdges) { return; //already deleted } if (AelPrev != null) { AelPrev.nextInAEL = AelNext; } else { activeEdges = AelNext; } if (AelNext != null) { AelNext.prevInAEL = AelPrev; } e.nextInAEL = null; e.prevInAEL = null; LOGGER.exiting( DefaultClipper.class.getName(), "deleteFromAEL" ); } private void deleteFromSEL( Edge e ) { LOGGER.entering( DefaultClipper.class.getName(), "deleteFromSEL" ); final Edge SelPrev = e.prevInSEL; final Edge SelNext = e.nextInSEL; if (SelPrev == null && SelNext == null && !e.equals( sortedEdges )) { return; //already deleted } if (SelPrev != null) { SelPrev.nextInSEL = SelNext; } else { sortedEdges = SelNext; } if (SelNext != null) { SelNext.prevInSEL = SelPrev; } e.nextInSEL = null; e.prevInSEL = null; } private boolean doHorzSegmentsOverlap( long seg1a, long seg1b, long seg2a, long seg2b ) { if (seg1a > seg1b) { final long tmp = seg1a; seg1a = seg1b; seg1b = tmp; } if (seg2a > seg2b) { final long tmp = seg2a; seg2a = seg2b; seg2b = tmp; } return (seg1a < seg2b) && (seg2a < seg1b); } private void doMaxima( Edge e ) { final Edge eMaxPair = e.getMaximaPair(); if (eMaxPair == null) { if (e.outIdx >= 0) { addOutPt( e, e.getTop() ); } deleteFromAEL( e ); return; } Edge eNext = e.nextInAEL; while (eNext != null && eNext != eMaxPair) { final LongPoint tmp = new LongPoint( e.getTop() ); intersectEdges( e, eNext, tmp ); e.setTop( tmp ); swapPositionsInAEL( e, eNext ); eNext = e.nextInAEL; } if (e.outIdx == Edge.UNASSIGNED && eMaxPair.outIdx == Edge.UNASSIGNED) { deleteFromAEL( e ); deleteFromAEL( eMaxPair ); } else if (e.outIdx >= 0 && eMaxPair.outIdx >= 0) { if (e.outIdx >= 0) { addLocalMaxPoly( e, eMaxPair, e.getTop() ); } deleteFromAEL( e ); deleteFromAEL( eMaxPair ); } else if (e.windDelta == 0) { if (e.outIdx >= 0) { addOutPt( e, e.getTop() ); e.outIdx = Edge.UNASSIGNED; } deleteFromAEL( e ); if (eMaxPair.outIdx >= 0) { addOutPt( eMaxPair, e.getTop() ); eMaxPair.outIdx = Edge.UNASSIGNED; } deleteFromAEL( eMaxPair ); } else { throw new IllegalStateException( "DoMaxima error" ); } } //------------------------------------------------------------------------------ private void doSimplePolygons() { int i = 0; while (i < polyOuts.size()) { final OutRec outrec = polyOuts.get( i++ ); Path.OutPt op = outrec.getPoints(); if (op == null || outrec.isOpen) { continue; } do //for each Pt in Polygon until duplicate found do ... { Path.OutPt op2 = op.next; while (op2 != outrec.getPoints()) { if (op.getPt().equals( op2.getPt() ) && !op2.next.equals( op ) && !op2.prev.equals( op )) { //split the polygon into two ... final Path.OutPt op3 = op.prev; final Path.OutPt op4 = op2.prev; op.prev = op4; op4.next = op; op2.prev = op3; op3.next = op2; outrec.setPoints( op ); final OutRec outrec2 = createOutRec(); outrec2.setPoints( op2 ); updateOutPtIdxs( outrec2 ); if (poly2ContainsPoly1( outrec2.getPoints(), outrec.getPoints() )) { //OutRec2 is contained by OutRec1 ... outrec2.isHole = !outrec.isHole; outrec2.firstLeft = outrec; if (usingPolyTree) { fixupFirstLefts2( outrec2, outrec ); } } else if (poly2ContainsPoly1( outrec.getPoints(), outrec2.getPoints() )) { //OutRec1 is contained by OutRec2 ... outrec2.isHole = outrec.isHole; outrec.isHole = !outrec2.isHole; outrec2.firstLeft = outrec.firstLeft; outrec.firstLeft = outrec2; if (usingPolyTree) { fixupFirstLefts2( outrec, outrec2 ); } } else { //the 2 polygons are separate ... outrec2.isHole = outrec.isHole; outrec2.firstLeft = outrec.firstLeft; if (usingPolyTree) { fixupFirstLefts1( outrec, outrec2 ); } } op2 = op; //ie get ready for the next iteration } op2 = op2.next; } op = op.next; } while (op != outrec.getPoints()); } } //------------------------------------------------------------------------------ private boolean EdgesAdjacent( IntersectNode inode ) { return inode.edge1.nextInSEL == inode.Edge2 || inode.edge1.prevInSEL == inode.Edge2; } //------------------------------------------------------------------------------ public boolean execute(ClipType clipType, Paths solution, PolyFillType FillType) { return execute(clipType, solution, FillType, FillType); } public boolean execute(ClipType clipType, PolyTree polytree) { return execute(clipType, polytree, PolyFillType.EVEN_ODD); } public boolean execute(ClipType clipType, PolyTree polytree, PolyFillType FillType) { return execute(clipType, polytree, FillType, FillType); } public boolean execute(ClipType clipType, Paths solution) { return execute(clipType, solution, PolyFillType.EVEN_ODD); } public boolean execute( ClipType clipType, Paths solution, PolyFillType subjFillType, PolyFillType clipFillType ) { synchronized (this) { if (hasOpenPaths) { throw new IllegalStateException( "Error: PolyTree struct is needed for open path clipping." ); } solution.clear(); this.subjFillType = subjFillType; this.clipFillType = clipFillType; this.clipType = clipType; usingPolyTree = false; boolean succeeded; try { succeeded = executeInternal(); //build the return polygons ... if (succeeded) { buildResult( solution ); } return succeeded; } finally { polyOuts.clear(); } } } public boolean execute( ClipType clipType, PolyTree polytree, PolyFillType subjFillType, PolyFillType clipFillType ) { synchronized (this) { this.subjFillType = subjFillType; this.clipFillType = clipFillType; this.clipType = clipType; usingPolyTree = true; boolean succeeded; try { succeeded = executeInternal(); //build the return polygons ... if (succeeded) { buildResult2( polytree ); } } finally { polyOuts.clear(); } return succeeded; } } //------------------------------------------------------------------------------ private boolean executeInternal() { try { reset(); if (currentLM == null) return false; long botY = popScanbeam(); do { insertLocalMinimaIntoAEL(botY); processHorizontals(); ghostJoins.clear(); if (scanbeam == null) break; long topY = popScanbeam(); if (!processIntersections(topY)) return false; processEdgesAtTopOfScanbeam(topY); botY = topY; } while (scanbeam != null || currentLM != null); //fix orientations ... for (int i = 0; i < polyOuts.size(); i++) { OutRec outRec = polyOuts.get(i); if (outRec.pts == null || outRec.isOpen) continue; if ((outRec.isHole ^ reverseSolution) == (outRec.area() > 0)) outRec.getPoints().reversePolyPtLinks(); } joinCommonEdges(); for (int i = 0; i < polyOuts.size(); i++) { OutRec outRec = polyOuts.get(i); if (outRec.getPoints() == null) continue; else if (outRec.isOpen) fixupOutPolyline(outRec); else fixupOutPolygon(outRec); } if (strictlySimple) doSimplePolygons(); return true; } //catch { return false; } finally { joins.clear(); ghostJoins.clear(); } } //------------------------------------------------------------------------------ private void fixupFirstLefts1( OutRec OldOutRec, OutRec NewOutRec ) { for (int i = 0; i < polyOuts.size(); i++) { final OutRec outRec = polyOuts.get( i ); if (outRec.getPoints() == null || outRec.firstLeft == null) { continue; } final OutRec firstLeft = parseFirstLeft(outRec.firstLeft); if (firstLeft.equals( OldOutRec )) { if (poly2ContainsPoly1( outRec.getPoints(), NewOutRec.getPoints() )) { outRec.firstLeft = NewOutRec; } } } } private void fixupFirstLefts2( OutRec OldOutRec, OutRec NewOutRec ) { for (final OutRec outRec : polyOuts) { if (outRec.firstLeft == OldOutRec ) { outRec.firstLeft = NewOutRec; } } } private boolean fixupIntersectionOrder() { //pre-condition: intersections are sorted bottom-most first. //Now it's crucial that intersections are made only between adjacent edges, //so to ensure this the order of intersections may need adjusting ... Collections.sort( intersectList, intersectNodeComparer ); copyAELToSEL(); final int cnt = intersectList.size(); for (int i = 0; i < cnt; i++) { if (!EdgesAdjacent( intersectList.get( i ) )) { int j = i + 1; while (j < cnt && !EdgesAdjacent( intersectList.get( j ) )) { j++; } if (j == cnt) { return false; } final IntersectNode tmp = intersectList.get( i ); intersectList.set( i, intersectList.get( j ) ); intersectList.set( j, tmp ); } swapPositionsInSEL( intersectList.get( i ).edge1, intersectList.get( i ).Edge2 ); } return true; } //---------------------------------------------------------------------- private void fixupOutPolyline(OutRec outrec) { Path.OutPt pp = outrec.pts; Path.OutPt lastPP = pp.prev; while (pp != lastPP) { pp = pp.next; if (pp.pt.equals(pp.prev.pt)) { if (pp == lastPP) lastPP = pp.prev; Path.OutPt tmpPP = pp.prev; tmpPP.next = pp.next; pp.next.prev = tmpPP; pp = tmpPP; } } if (pp == pp.prev) outrec.pts = null; } private void fixupOutPolygon( OutRec outRec ) { //FixupOutPolygon() - removes duplicate points and simplifies consecutive //parallel edges by removing the middle vertex. Path.OutPt lastOK = null; outRec.bottomPt = null; Path.OutPt pp = outRec.getPoints(); boolean preserveCol = preserveCollinear || strictlySimple; for (;;) { if (pp.prev == pp || pp.prev == pp.next) { outRec.setPoints( null ); return; } //test for duplicate points and collinear edges ... if (pp.getPt().equals( pp.next.getPt() ) || pp.getPt().equals( pp.prev.getPt() ) || Point.slopesEqual( pp.prev.getPt(), pp.getPt(), pp.next.getPt(), useFullRange ) && (!preserveCol || !Point.isPt2BetweenPt1AndPt3( pp.prev.getPt(), pp.getPt(), pp.next.getPt() ))) { lastOK = null; pp.prev.next = pp.next; pp.next.prev = pp.prev; pp = pp.prev; } else if (pp == lastOK) { break; } else { if (lastOK == null) { lastOK = pp; } pp = pp.next; } } outRec.setPoints( pp ); } private OutRec getOutRec( int idx ) { OutRec outrec = polyOuts.get( idx ); while (outrec != polyOuts.get( outrec.Idx )) { outrec = polyOuts.get( outrec.Idx ); } return outrec; } private void insertEdgeIntoAEL( Edge edge, Edge startEdge ) { LOGGER.entering( DefaultClipper.class.getName(), "insertEdgeIntoAEL" ); if (activeEdges == null) { edge.prevInAEL = null; edge.nextInAEL = null; LOGGER.finest( "Edge " + edge.outIdx + " -> " + null ); activeEdges = edge; } else if (startEdge == null && Edge.doesE2InsertBeforeE1( activeEdges, edge )) { edge.prevInAEL = null; edge.nextInAEL = activeEdges; LOGGER.finest( "Edge " + edge.outIdx + " -> " + edge.nextInAEL.outIdx ); activeEdges.prevInAEL = edge; activeEdges = edge; } else { LOGGER.finest( "activeEdges unchanged" ); if (startEdge == null) { startEdge = activeEdges; } while (startEdge.nextInAEL != null && !Edge.doesE2InsertBeforeE1( startEdge.nextInAEL, edge )) { startEdge = startEdge.nextInAEL; } edge.nextInAEL = startEdge.nextInAEL; if (startEdge.nextInAEL != null) { startEdge.nextInAEL.prevInAEL = edge; } edge.prevInAEL = startEdge; startEdge.nextInAEL = edge; } } //------------------------------------------------------------------------------ private void insertLocalMinimaIntoAEL( long botY ) { LOGGER.entering( DefaultClipper.class.getName(), "insertLocalMinimaIntoAEL" ); while (currentLM != null && currentLM.y == botY) { final Edge lb = currentLM.leftBound; final Edge rb = currentLM.rightBound; popLocalMinima(); Path.OutPt Op1 = null; if (lb == null) { insertEdgeIntoAEL( rb, null ); updateWindingCount( rb ); if (rb.isContributing( clipFillType, subjFillType, clipType )) { Op1 = addOutPt( rb, rb.getBot() ); } } else if (rb == null) { insertEdgeIntoAEL( lb, null ); updateWindingCount( lb ); if (lb.isContributing( clipFillType, subjFillType, clipType )) { Op1 = addOutPt( lb, lb.getBot() ); } insertScanbeam( lb.getTop().getY() ); } else { insertEdgeIntoAEL( lb, null ); insertEdgeIntoAEL( rb, lb ); updateWindingCount( lb ); rb.windCnt = lb.windCnt; rb.windCnt2 = lb.windCnt2; if (lb.isContributing( clipFillType, subjFillType, clipType )) { Op1 = addLocalMinPoly( lb, rb, lb.getBot() ); } insertScanbeam( lb.getTop().getY() ); } if (rb != null) { if (rb.isHorizontal()) { addEdgeToSEL( rb ); } else { insertScanbeam( rb.getTop().getY() ); } } if (lb == null || rb == null) { continue; } //if output polygons share an Edge with a horizontal rb, they'll need joining later ... if (Op1 != null && rb.isHorizontal() && ghostJoins.size() > 0 && rb.windDelta != 0) { for (int i = 0; i < ghostJoins.size(); i++) { //if the horizontal Rb and a 'ghost' horizontal overlap, then convert //the 'ghost' join to a real join ready for later ... final Join j = ghostJoins.get( i ); if (doHorzSegmentsOverlap( j.outPt1.getPt().getX(), j.getOffPt().getX(), rb.getBot().getX(), rb.getTop().getX() )) { addJoin( j.outPt1, Op1, j.getOffPt() ); } } } if (lb.outIdx >= 0 && lb.prevInAEL != null && lb.prevInAEL.getCurrent().getX() == lb.getBot().getX() && lb.prevInAEL.outIdx >= 0 && Edge.slopesEqual( lb.prevInAEL, lb, useFullRange ) && lb.windDelta != 0 && lb.prevInAEL.windDelta != 0) { final Path.OutPt Op2 = addOutPt( lb.prevInAEL, lb.getBot() ); addJoin( Op1, Op2, lb.getTop() ); } if (lb.nextInAEL != rb) { if (rb.outIdx >= 0 && rb.prevInAEL.outIdx >= 0 && Edge.slopesEqual( rb.prevInAEL, rb, useFullRange ) && rb.windDelta != 0 && rb.prevInAEL.windDelta != 0) { final Path.OutPt Op2 = addOutPt( rb.prevInAEL, rb.getBot() ); addJoin( Op1, Op2, rb.getTop() ); } Edge e = lb.nextInAEL; if (e != null) { while (e != rb) { //nb: For calculating winding counts etc, IntersectEdges() assumes //that param1 will be to the right of param2 ABOVE the intersection ... intersectEdges( rb, e, lb.getCurrent() ); //order important here e = e.nextInAEL; } } } } } //------------------------------------------------------------------------------ // private void insertScanbeam( long y ) { // LOGGER.entering( DefaultClipper.class.getName(), "insertScanbeam" ); // // if (scanbeam == null) { // scanbeam = new Scanbeam(); // scanbeam.next = null; // scanbeam.y = y; // } // else if (y > scanbeam.y) { // final Scanbeam newSb = new Scanbeam(); // newSb.y = y; // newSb.next = scanbeam; // scanbeam = newSb; // } // else { // Scanbeam sb2 = scanbeam; // while (sb2.next != null && y <= sb2.next.y) { // sb2 = sb2.next; // } // if (y == sb2.y) { // return; //ie ignores duplicates // } // final Scanbeam newSb = new Scanbeam(); // newSb.y = y; // newSb.next = sb2.next; // sb2.next = newSb; // } // } //------------------------------------------------------------------------------ private void intersectEdges( Edge e1, Edge e2, LongPoint pt ) { LOGGER.entering( DefaultClipper.class.getName(), "insersectEdges" ); //e1 will be to the left of e2 BELOW the intersection. Therefore e1 is before //e2 in AEL except when e1 is being inserted at the intersection point ... final boolean e1Contributing = e1.outIdx >= 0; final boolean e2Contributing = e2.outIdx >= 0; setZ( pt, e1, e2 ); //if either edge is on an OPEN path ... if (e1.windDelta == 0 || e2.windDelta == 0) { //ignore subject-subject open path intersections UNLESS they //are both open paths, AND they are both 'contributing maximas' ... if (e1.windDelta == 0 && e2.windDelta == 0) { return; } else if (e1.polyTyp == e2.polyTyp && e1.windDelta != e2.windDelta && clipType == ClipType.UNION) { if (e1.windDelta == 0) { if (e2Contributing) { addOutPt( e1, pt ); if (e1Contributing) { e1.outIdx = Edge.UNASSIGNED; } } } else { if (e1Contributing) { addOutPt( e2, pt ); if (e2Contributing) { e2.outIdx = Edge.UNASSIGNED; } } } } else if (e1.polyTyp != e2.polyTyp) { if (e1.windDelta == 0 && Math.abs( e2.windCnt ) == 1 && (clipType != ClipType.UNION || e2.windCnt2 == 0)) { addOutPt( e1, pt ); if (e1Contributing) { e1.outIdx = Edge.UNASSIGNED; } } else if (e2.windDelta == 0 && Math.abs( e1.windCnt ) == 1 && (clipType != ClipType.UNION || e1.windCnt2 == 0)) { addOutPt( e2, pt ); if (e2Contributing) { e2.outIdx = Edge.UNASSIGNED; } } } return; } //update winding counts... //assumes that e1 will be to the Right of e2 ABOVE the intersection if (e1.polyTyp == e2.polyTyp) { if (e1.isEvenOddFillType( clipFillType, subjFillType )) { final int oldE1WindCnt = e1.windCnt; e1.windCnt = e2.windCnt; e2.windCnt = oldE1WindCnt; } else { if (e1.windCnt + e2.windDelta == 0) { e1.windCnt = -e1.windCnt; } else { e1.windCnt += e2.windDelta; } if (e2.windCnt - e1.windDelta == 0) { e2.windCnt = -e2.windCnt; } else { e2.windCnt -= e1.windDelta; } } } else { if (!e2.isEvenOddFillType( clipFillType, subjFillType )) { e1.windCnt2 += e2.windDelta; } else { e1.windCnt2 = e1.windCnt2 == 0 ? 1 : 0; } if (!e1.isEvenOddFillType( clipFillType, subjFillType )) { e2.windCnt2 -= e1.windDelta; } else { e2.windCnt2 = e2.windCnt2 == 0 ? 1 : 0; } } PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2; if (e1.polyTyp == PolyType.SUBJECT) { e1FillType = subjFillType; e1FillType2 = clipFillType; } else { e1FillType = clipFillType; e1FillType2 = subjFillType; } if (e2.polyTyp == PolyType.SUBJECT) { e2FillType = subjFillType; e2FillType2 = clipFillType; } else { e2FillType = clipFillType; e2FillType2 = subjFillType; } int e1Wc, e2Wc; switch (e1FillType) { case POSITIVE: e1Wc = e1.windCnt; break; case NEGATIVE: e1Wc = -e1.windCnt; break; default: e1Wc = Math.abs( e1.windCnt ); break; } switch (e2FillType) { case POSITIVE: e2Wc = e2.windCnt; break; case NEGATIVE: e2Wc = -e2.windCnt; break; default: e2Wc = Math.abs( e2.windCnt ); break; } if (e1Contributing && e2Contributing) { if (e1Wc != 0 && e1Wc != 1 || e2Wc != 0 && e2Wc != 1 || e1.polyTyp != e2.polyTyp && clipType != ClipType.XOR) { addLocalMaxPoly( e1, e2, pt ); } else { addOutPt( e1, pt ); addOutPt( e2, pt ); Edge.swapSides( e1, e2 ); Edge.swapPolyIndexes( e1, e2 ); } } else if (e1Contributing) { if (e2Wc == 0 || e2Wc == 1) { addOutPt( e1, pt ); Edge.swapSides( e1, e2 ); Edge.swapPolyIndexes( e1, e2 ); } } else if (e2Contributing) { if (e1Wc == 0 || e1Wc == 1) { addOutPt( e2, pt ); Edge.swapSides( e1, e2 ); Edge.swapPolyIndexes( e1, e2 ); } } else if ((e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1)) { //neither edge is currently contributing ... int e1Wc2, e2Wc2; switch (e1FillType2) { case POSITIVE: e1Wc2 = e1.windCnt2; break; case NEGATIVE: e1Wc2 = -e1.windCnt2; break; default: e1Wc2 = Math.abs( e1.windCnt2 ); break; } switch (e2FillType2) { case POSITIVE: e2Wc2 = e2.windCnt2; break; case NEGATIVE: e2Wc2 = -e2.windCnt2; break; default: e2Wc2 = Math.abs( e2.windCnt2 ); break; } if (e1.polyTyp != e2.polyTyp) { addLocalMinPoly( e1, e2, pt ); } else if (e1Wc == 1 && e2Wc == 1) { switch (clipType) { case INTERSECTION: if (e1Wc2 > 0 && e2Wc2 > 0) { addLocalMinPoly( e1, e2, pt ); } break; case UNION: if (e1Wc2 <= 0 && e2Wc2 <= 0) { addLocalMinPoly( e1, e2, pt ); } break; case DIFFERENCE: if (e1.polyTyp == PolyType.CLIP && e1Wc2 > 0 && e2Wc2 > 0 || e1.polyTyp == PolyType.SUBJECT && e1Wc2 <= 0 && e2Wc2 <= 0) { addLocalMinPoly( e1, e2, pt ); } break; case XOR: addLocalMinPoly( e1, e2, pt ); break; } } else { Edge.swapSides( e1, e2 ); } } } private void intersectPoint( Edge edge1, Edge edge2, LongPoint[] ipV ) { final LongPoint ip = ipV[0] = new LongPoint(); double b1, b2; //nb: with very large coordinate values, it's possible for SlopesEqual() to //return false but for the edge.Dx value be equal due to double precision rounding. if (edge1.deltaX == edge2.deltaX) { ip.setY( edge1.getCurrent().getY() ); ip.setX( Edge.topX( edge1, ip.getY() ) ); return; } if (edge1.getDelta().getX() == 0) { ip.setX( edge1.getBot().getX() ); if (edge2.isHorizontal()) { ip.setY( edge2.getBot().getY() ); } else { b2 = edge2.getBot().getY() - edge2.getBot().getX() / edge2.deltaX; ip.setY( Math.round( ip.getX() / edge2.deltaX + b2 ) ); } } else if (edge2.getDelta().getX() == 0) { ip.setX( edge2.getBot().getX() ); if (edge1.isHorizontal()) { ip.setY( edge1.getBot().getY() ); } else { b1 = edge1.getBot().getY() - edge1.getBot().getX() / edge1.deltaX; ip.setY( Math.round( ip.getX() / edge1.deltaX + b1 ) ); } } else { b1 = edge1.getBot().getX() - edge1.getBot().getY() * edge1.deltaX; b2 = edge2.getBot().getX() - edge2.getBot().getY() * edge2.deltaX; final double q = (b2 - b1) / (edge1.deltaX - edge2.deltaX); ip.setY( Math.round( q ) ); if (Math.abs( edge1.deltaX ) < Math.abs( edge2.deltaX )) { ip.setX( Math.round( edge1.deltaX * q + b1 ) ); } else { ip.setX( Math.round( edge2.deltaX * q + b2 ) ); } } if (ip.getY() < edge1.getTop().getY() || ip.getY() < edge2.getTop().getY()) { if (edge1.getTop().getY() > edge2.getTop().getY()) { ip.setY( edge1.getTop().getY() ); } else { ip.setY( edge2.getTop().getY() ); } if (Math.abs( edge1.deltaX ) < Math.abs( edge2.deltaX )) { ip.setX( Edge.topX( edge1, ip.getY() ) ); } else { ip.setX( Edge.topX( edge2, ip.getY() ) ); } } //finally, don't allow 'ip' to be BELOW curr.getY() (ie bottom of scanbeam) ... if (ip.getY() > edge1.getCurrent().getY()) { ip.setY( edge1.getCurrent().getY() ); //better to use the more vertical edge to derive X ... if (Math.abs( edge1.deltaX ) > Math.abs( edge2.deltaX )) { ip.setX( Edge.topX( edge2, ip.getY() ) ); } else { ip.setX( Edge.topX( edge1, ip.getY() ) ); } } } private void joinCommonEdges() { for (int i = 0; i < joins.size(); i++) { final Join join = joins.get( i ); final OutRec outRec1 = getOutRec( join.outPt1.idx ); OutRec outRec2 = getOutRec( join.outPt2.idx ); if (outRec1.getPoints() == null || outRec2.getPoints() == null) { continue; } if (outRec1.isOpen || outRec2.isOpen) continue; //get the polygon fragment with the correct hole state (FirstLeft) //before calling JoinPoints() ... OutRec holeStateRec; if (outRec1 == outRec2) { holeStateRec = outRec1; } else if (isParam1RightOfParam2( outRec1, outRec2 )) { holeStateRec = outRec2; } else if (isParam1RightOfParam2( outRec2, outRec1 )) { holeStateRec = outRec1; } else { holeStateRec = Path.OutPt.getLowerMostRec( outRec1, outRec2 ); } if (!joinPoints( join, outRec1, outRec2 )) { continue; } if (outRec1 == outRec2) { //instead of joining two polygons, we've just created a new one by //splitting one polygon into two. outRec1.setPoints( join.outPt1 ); outRec1.bottomPt = null; outRec2 = createOutRec(); outRec2.setPoints( join.outPt2 ); //update all OutRec2.Pts Idx's ... updateOutPtIdxs( outRec2 ); //We now need to check every OutRec.FirstLeft pointer. If it points //to OutRec1 it may need to point to OutRec2 instead ... if (usingPolyTree) { for (int j = 0; j < polyOuts.size() - 1; j++) { final OutRec oRec = polyOuts.get( j ); if (oRec.getPoints() == null || parseFirstLeft(oRec.firstLeft) != outRec1 || oRec.isHole == outRec1.isHole) { continue; } if (poly2ContainsPoly1( oRec.getPoints(), join.outPt2 )) { oRec.firstLeft = outRec2; } } } if (poly2ContainsPoly1( outRec2.getPoints(), outRec1.getPoints() )) { //outRec2 is contained by outRec1 ... outRec2.isHole = !outRec1.isHole; outRec2.firstLeft = outRec1; //fixup FirstLeft pointers that may need reassigning to OutRec1 if (usingPolyTree) { fixupFirstLefts2( outRec2, outRec1 ); } if ((outRec2.isHole ^ reverseSolution) == outRec2.area() > 0) { outRec2.getPoints().reversePolyPtLinks(); } } else if (poly2ContainsPoly1( outRec1.getPoints(), outRec2.getPoints() )) { //outRec1 is contained by outRec2 ... outRec2.isHole = outRec1.isHole; outRec1.isHole = !outRec2.isHole; outRec2.firstLeft = outRec1.firstLeft; outRec1.firstLeft = outRec2; //fixup FirstLeft pointers that may need reassigning to OutRec1 if (usingPolyTree) { fixupFirstLefts2( outRec1, outRec2 ); } if ((outRec1.isHole ^ reverseSolution) == outRec1.area() > 0) { outRec1.getPoints().reversePolyPtLinks(); } } else { //the 2 polygons are completely separate ... outRec2.isHole = outRec1.isHole; outRec2.firstLeft = outRec1.firstLeft; //fixup FirstLeft pointers that may need reassigning to OutRec2 if (usingPolyTree) { fixupFirstLefts1( outRec1, outRec2 ); } } } else { //joined 2 polygons together ... outRec2.setPoints( null ); outRec2.bottomPt = null; outRec2.Idx = outRec1.Idx; outRec1.isHole = holeStateRec.isHole; if (holeStateRec == outRec2) { outRec1.firstLeft = outRec2.firstLeft; } outRec2.firstLeft = outRec1; //fixup FirstLeft pointers that may need reassigning to OutRec1 if (usingPolyTree) { fixupFirstLefts2( outRec2, outRec1 ); } } } } private long popScanbeam() { LOGGER.entering( DefaultClipper.class.getName(), "popBeam" ); final long y = scanbeam.y; scanbeam = scanbeam.next; return y; } private void processEdgesAtTopOfScanbeam( long topY ) { LOGGER.entering( DefaultClipper.class.getName(), "processEdgesAtTopOfScanbeam" ); Edge e = activeEdges; while (e != null) { //1. process maxima, treating them as if they're 'bent' horizontal edges, // but exclude maxima with horizontal edges. nb: e can't be a horizontal. boolean IsMaximaEdge = e.isMaxima( topY ); if (IsMaximaEdge) { final Edge eMaxPair = e.getMaximaPair(); IsMaximaEdge = eMaxPair == null || !eMaxPair.isHorizontal(); } if (IsMaximaEdge) { if (strictlySimple) InsertMaxima(e.getTop().getX()); final Edge ePrev = e.prevInAEL; doMaxima( e ); if (ePrev == null) { e = activeEdges; } else { e = ePrev.nextInAEL; } } else { //2. promote horizontal edges, otherwise update Curr.getX() and Curr.getY() ... if (e.isIntermediate( topY ) && e.nextInLML.isHorizontal()) { final Edge[] t = new Edge[] { e }; updateEdgeIntoAEL( t ); e = t[0]; if (e.outIdx >= 0) { addOutPt( e, e.getBot() ); } addEdgeToSEL( e ); } else { e.getCurrent().setX( Edge.topX( e, topY ) ); e.getCurrent().setY( topY ); } //When StrictlySimple and 'e' is being touched by another edge, then //make sure both edges have a vertex here ... if (strictlySimple) { final Edge ePrev = e.prevInAEL; if (e.outIdx >= 0 && e.windDelta != 0 && ePrev != null && ePrev.outIdx >= 0 && ePrev.getCurrent().getX() == e.getCurrent().getX() && ePrev.windDelta != 0) { final LongPoint ip = new LongPoint( e.getCurrent() ); setZ( ip, ePrev, e ); final Path.OutPt op = addOutPt( ePrev, ip ); final Path.OutPt op2 = addOutPt( e, ip ); addJoin( op, op2, ip ); //StrictlySimple (type-3) join } } e = e.nextInAEL; } } //3. Process horizontals at the Top of the scanbeam ... processHorizontals(); maxima = null; //4. Promote intermediate vertices ... e = activeEdges; while (e != null) { if (e.isIntermediate( topY )) { Path.OutPt op = null; if (e.outIdx >= 0) { op = addOutPt( e, e.getTop() ); } final Edge[] t = new Edge[] { e }; updateEdgeIntoAEL( t ); e = t[0]; //if output polygons share an edge, they'll need joining later ... final Edge ePrev = e.prevInAEL; final Edge eNext = e.nextInAEL; if (ePrev != null && ePrev.getCurrent().getX() == e.getBot().getX() && ePrev.getCurrent().getY() == e.getBot().getY() && op != null && ePrev.outIdx >= 0 && ePrev.getCurrent().getY() > ePrev.getTop().getY() && Edge.slopesEqual( e, ePrev, useFullRange ) && e.windDelta != 0 && ePrev.windDelta != 0) { final Path.OutPt op2 = addOutPt( ePrev, e.getBot() ); addJoin( op, op2, e.getTop() ); } else if (eNext != null && eNext.getCurrent().getX() == e.getBot().getX() && eNext.getCurrent().getY() == e.getBot().getY() && op != null && eNext.outIdx >= 0 && eNext.getCurrent().getY() > eNext.getTop().getY() && Edge.slopesEqual( e, eNext, useFullRange ) && e.windDelta != 0 && eNext.windDelta != 0) { final Path.OutPt op2 = addOutPt( eNext, e.getBot() ); addJoin( op, op2, e.getTop() ); } } e = e.nextInAEL; } LOGGER.exiting( DefaultClipper.class.getName(), "processEdgesAtTopOfScanbeam" ); } private void processHorizontal( Edge horzEdge ) { LOGGER.entering( DefaultClipper.class.getName(), "isHorizontal" ); final Direction[] dir = new Direction[1]; final long[] horzLeft = new long[1], horzRight = new long[1]; boolean IsOpen = horzEdge.outIdx >= 0 && polyOuts.get(horzEdge.outIdx).isOpen; getHorzDirection( horzEdge, dir, horzLeft, horzRight ); Edge eLastHorz = horzEdge, eMaxPair = null; while (eLastHorz.nextInLML != null && eLastHorz.nextInLML.isHorizontal()) { eLastHorz = eLastHorz.nextInLML; } if (eLastHorz.nextInLML == null) { eMaxPair = eLastHorz.getMaximaPair(); } Path.Maxima currMax = maxima; if (currMax != null) { //get the first maxima in range (X) ... if (dir[0] == Direction.LEFT_TO_RIGHT) { while (currMax != null && currMax.X <= horzEdge.getBot().getX()) currMax = currMax.Next; if (currMax != null && currMax.X >= eLastHorz.getBot().getX()) currMax = null; } else { while (currMax.Next != null && currMax.Next.X < horzEdge.getBot().getX()) currMax = currMax.Next; if (currMax.X <= eLastHorz.getTop().getX()) currMax = null; } } Path.OutPt op1 = null; for (;;) { //loop through consec. horizontal edges final boolean IsLastHorz = horzEdge == eLastHorz; Edge e = horzEdge.getNextInAEL( dir[0] ); while (e != null) { //this code block inserts extra coords into horizontal edges (in output //polygons) whereever maxima touch these horizontal edges. This helps //'simplifying' polygons (ie if the Simplify property is set). if (currMax != null) { if (dir[0] == Direction.LEFT_TO_RIGHT) { while (currMax != null && currMax.X < e.getCurrent().getX()) { if (horzEdge.outIdx >= 0 && !IsOpen) addOutPt(horzEdge, new LongPoint(currMax.X, horzEdge.getBot().getY())); currMax = currMax.Next; } } else { while (currMax != null && currMax.X > e.getCurrent().getX()) { if (horzEdge.outIdx >= 0 && !IsOpen) addOutPt(horzEdge, new LongPoint(currMax.X, horzEdge.getBot().getY())); currMax = currMax.Prev; } } }; if (dir[0] == Direction.LEFT_TO_RIGHT && e.getCurrent().getX() > horzRight[0] || dir[0] == Direction.RIGHT_TO_LEFT && e.getCurrent().getX() < horzLeft[0]) break; //Also break if we've got to the end of an intermediate horizontal edge ... //nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal. if (e.getCurrent().getX() == horzEdge.getTop().getX() && horzEdge.nextInLML != null && e.deltaX < horzEdge.nextInLML.deltaX) break; if (horzEdge.outIdx >= 0 && !IsOpen) //note: may be done multiple times { op1 = addOutPt(horzEdge, e.getCurrent()); Edge eNextHorz = sortedEdges; while (eNextHorz != null) { if (eNextHorz.outIdx >= 0 && doHorzSegmentsOverlap(horzEdge.getBot().getX(), horzEdge.getTop().getX(), eNextHorz.getBot().getX(), eNextHorz.getTop().getX())) { Path.OutPt op2 = GetLastOutPt(eNextHorz); addJoin(op2, op1, eNextHorz.getTop()); } eNextHorz = eNextHorz.nextInSEL; } addGhostJoin(op1, horzEdge.getBot()); } //OK, so far we're still in range of the horizontal Edge but make sure //we're at the last of consec. horizontals when matching with eMaxPair if(e == eMaxPair && IsLastHorz) { if (horzEdge.outIdx >= 0) addLocalMaxPoly(horzEdge, eMaxPair, horzEdge.getTop()); deleteFromAEL(horzEdge); deleteFromAEL(eMaxPair); return; } if(dir[0] == Direction.LEFT_TO_RIGHT) { LongPoint Pt = new LongPoint(e.getCurrent().getX(), horzEdge.getCurrent().getY()); intersectEdges(horzEdge, e, Pt); } else { LongPoint Pt = new LongPoint(e.getCurrent().getX(), horzEdge.getCurrent().getY()); intersectEdges(e, horzEdge, Pt); } Edge eNext = e.getNextInAEL(dir[0]); swapPositionsInAEL(horzEdge, e); e = eNext; } //end while //Break out of loop if HorzEdge.NextInLML is not also horizontal ... if (horzEdge.nextInLML == null || !horzEdge.nextInLML.isHorizontal()) break; Edge[] temp = new Edge[1]; temp[0] = horzEdge; updateEdgeIntoAEL(temp); horzEdge = temp[0]; if (horzEdge.outIdx >= 0) addOutPt(horzEdge, horzEdge.getBot()); getHorzDirection(horzEdge, dir, horzLeft, horzRight); } //end for (;;) if (horzEdge.outIdx >= 0 && op1 == null) { op1 = GetLastOutPt(horzEdge); Edge eNextHorz = sortedEdges; while (eNextHorz != null) { if (eNextHorz.outIdx >= 0 && doHorzSegmentsOverlap(horzEdge.getBot().getX(), horzEdge.getTop().getX(), eNextHorz.getBot().getX(), eNextHorz.getTop().getX())) { Path.OutPt op2 = GetLastOutPt(eNextHorz); addJoin(op2, op1, eNextHorz.getTop()); } eNextHorz = eNextHorz.nextInSEL; } addGhostJoin(op1, horzEdge.getTop()); } if (horzEdge.nextInLML != null) { if (horzEdge.outIdx >= 0) { op1 = addOutPt( horzEdge, horzEdge.getTop()); final Edge[] t = new Edge[] { horzEdge }; updateEdgeIntoAEL( t ); horzEdge = t[0]; if (horzEdge.windDelta == 0) { return; } //nb: HorzEdge is no longer horizontal here final Edge ePrev = horzEdge.prevInAEL; final Edge eNext = horzEdge.nextInAEL; if (ePrev != null && ePrev.getCurrent().getX() == horzEdge.getBot().getX() && ePrev.getCurrent().getY() == horzEdge.getBot().getY() && ePrev.windDelta != 0 && ePrev.outIdx >= 0 && ePrev.getCurrent().getY() > ePrev.getTop().getY() && Edge.slopesEqual( horzEdge, ePrev, useFullRange )) { final Path.OutPt op2 = addOutPt( ePrev, horzEdge.getBot() ); addJoin( op1, op2, horzEdge.getTop() ); } else if (eNext != null && eNext.getCurrent().getX() == horzEdge.getBot().getX() && eNext.getCurrent().getY() == horzEdge.getBot().getY() && eNext.windDelta != 0 && eNext.outIdx >= 0 && eNext.getCurrent().getY() > eNext.getTop().getY() && Edge.slopesEqual( horzEdge, eNext, useFullRange )) { final Path.OutPt op2 = addOutPt( eNext, horzEdge.getBot() ); addJoin( op1, op2, horzEdge.getTop() ); } } else { final Edge[] t = new Edge[] { horzEdge }; updateEdgeIntoAEL( t ); horzEdge = t[0]; } } else { if (horzEdge.outIdx >= 0) { addOutPt( horzEdge, horzEdge.getTop() ); } deleteFromAEL( horzEdge ); } } //------------------------------------------------------------------------------ private void processHorizontals( ) { LOGGER.entering( DefaultClipper.class.getName(), "processHorizontals" ); Edge horzEdge = sortedEdges; while (horzEdge != null) { deleteFromSEL( horzEdge ); processHorizontal( horzEdge); horzEdge = sortedEdges; } } //------------------------------------------------------------------------------ private boolean processIntersections( long topY ) { LOGGER.entering( DefaultClipper.class.getName(), "processIntersections" ); if (activeEdges == null) { return true; } try { buildIntersectList( topY ); if (intersectList.size() == 0) { return true; } if (intersectList.size() == 1 || fixupIntersectionOrder()) { processIntersectList(); } else { return false; } } catch (final Exception e) { sortedEdges = null; intersectList.clear(); throw new IllegalStateException( "ProcessIntersections error", e ); } sortedEdges = null; return true; } private void processIntersectList() { for (int i = 0; i < intersectList.size(); i++) { final IntersectNode iNode = intersectList.get( i ); { intersectEdges( iNode.edge1, iNode.Edge2, iNode.getPt() ); swapPositionsInAEL( iNode.edge1, iNode.Edge2 ); } } intersectList.clear(); } //------------------------------------------------------------------------------ @Override protected void reset() { super.reset(); scanbeam = null; maxima = null; activeEdges = null; sortedEdges = null; LocalMinima lm = minimaList; while (lm != null) { insertScanbeam( lm.y ); lm = lm.next; } } private void setHoleState( Edge e, OutRec outRec ) { boolean isHole = false; Edge e2 = e.prevInAEL; while (e2 != null) { if (e2.outIdx >= 0 && e2.windDelta != 0) { isHole = !isHole; if (outRec.firstLeft == null) { outRec.firstLeft = polyOuts.get( e2.outIdx ); } } e2 = e2.prevInAEL; } if (isHole) { outRec.isHole = true; } } private void setZ( LongPoint pt, Edge e1, Edge e2 ) { if (pt.getZ() != 0 || zFillFunction == null) { return; } else if (pt.equals( e1.getBot() )) { pt.setZ( e1.getBot().getZ() ); } else if (pt.equals( e1.getTop() )) { pt.setZ( e1.getTop().getZ() ); } else if (pt.equals( e2.getBot() )) { pt.setZ( e2.getBot().getZ() ); } else if (pt.equals( e2.getTop() )) { pt.setZ( e2.getTop().getZ() ); } else { zFillFunction.zFill( e1.getBot(), e1.getTop(), e2.getBot(), e2.getTop(), pt ); } } private void swapPositionsInAEL( Edge edge1, Edge edge2 ) { LOGGER.entering( DefaultClipper.class.getName(), "swapPositionsInAEL" ); //check that one or other edge hasn't already been removed from AEL ... if (edge1.nextInAEL == edge1.prevInAEL || edge2.nextInAEL == edge2.prevInAEL) { return; } if (edge1.nextInAEL == edge2) { final Edge next = edge2.nextInAEL; if (next != null) { next.prevInAEL = edge1; } final Edge prev = edge1.prevInAEL; if (prev != null) { prev.nextInAEL = edge2; } edge2.prevInAEL = prev; edge2.nextInAEL = edge1; edge1.prevInAEL = edge2; edge1.nextInAEL = next; } else if (edge2.nextInAEL == edge1) { final Edge next = edge1.nextInAEL; if (next != null) { next.prevInAEL = edge2; } final Edge prev = edge2.prevInAEL; if (prev != null) { prev.nextInAEL = edge1; } edge1.prevInAEL = prev; edge1.nextInAEL = edge2; edge2.prevInAEL = edge1; edge2.nextInAEL = next; } else { final Edge next = edge1.nextInAEL; final Edge prev = edge1.prevInAEL; edge1.nextInAEL = edge2.nextInAEL; if (edge1.nextInAEL != null) { edge1.nextInAEL.prevInAEL = edge1; } edge1.prevInAEL = edge2.prevInAEL; if (edge1.prevInAEL != null) { edge1.prevInAEL.nextInAEL = edge1; } edge2.nextInAEL = next; if (edge2.nextInAEL != null) { edge2.nextInAEL.prevInAEL = edge2; } edge2.prevInAEL = prev; if (edge2.prevInAEL != null) { edge2.prevInAEL.nextInAEL = edge2; } } if (edge1.prevInAEL == null) { activeEdges = edge1; } else if (edge2.prevInAEL == null) { activeEdges = edge2; } LOGGER.exiting( DefaultClipper.class.getName(), "swapPositionsInAEL" ); } //------------------------------------------------------------------------------; private void swapPositionsInSEL( Edge edge1, Edge edge2 ) { if (edge1.nextInSEL == null && edge1.prevInSEL == null) { return; } if (edge2.nextInSEL == null && edge2.prevInSEL == null) { return; } if (edge1.nextInSEL == edge2) { final Edge next = edge2.nextInSEL; if (next != null) { next.prevInSEL = edge1; } final Edge prev = edge1.prevInSEL; if (prev != null) { prev.nextInSEL = edge2; } edge2.prevInSEL = prev; edge2.nextInSEL = edge1; edge1.prevInSEL = edge2; edge1.nextInSEL = next; } else if (edge2.nextInSEL == edge1) { final Edge next = edge1.nextInSEL; if (next != null) { next.prevInSEL = edge2; } final Edge prev = edge2.prevInSEL; if (prev != null) { prev.nextInSEL = edge1; } edge1.prevInSEL = prev; edge1.nextInSEL = edge2; edge2.prevInSEL = edge1; edge2.nextInSEL = next; } else { final Edge next = edge1.nextInSEL; final Edge prev = edge1.prevInSEL; edge1.nextInSEL = edge2.nextInSEL; if (edge1.nextInSEL != null) { edge1.nextInSEL.prevInSEL = edge1; } edge1.prevInSEL = edge2.prevInSEL; if (edge1.prevInSEL != null) { edge1.prevInSEL.nextInSEL = edge1; } edge2.nextInSEL = next; if (edge2.nextInSEL != null) { edge2.nextInSEL.prevInSEL = edge2; } edge2.prevInSEL = prev; if (edge2.prevInSEL != null) { edge2.prevInSEL.nextInSEL = edge2; } } if (edge1.prevInSEL == null) { sortedEdges = edge1; } else if (edge2.prevInSEL == null) { sortedEdges = edge2; } } private void updateEdgeIntoAEL( Edge[] eV ) { Edge e = eV[0]; if (e.nextInLML == null) { throw new IllegalStateException( "UpdateEdgeIntoAEL: invalid call" ); } final Edge AelPrev = e.prevInAEL; final Edge AelNext = e.nextInAEL; e.nextInLML.outIdx = e.outIdx; if (AelPrev != null) { AelPrev.nextInAEL = e.nextInLML; } else { activeEdges = e.nextInLML; } if (AelNext != null) { AelNext.prevInAEL = e.nextInLML; } e.nextInLML.side = e.side; e.nextInLML.windDelta = e.windDelta; e.nextInLML.windCnt = e.windCnt; e.nextInLML.windCnt2 = e.windCnt2; eV[0] = e = e.nextInLML; e.setCurrent( e.getBot() ); e.prevInAEL = AelPrev; e.nextInAEL = AelNext; if (!e.isHorizontal()) { insertScanbeam( e.getTop().getY() ); } } private void updateOutPtIdxs( OutRec outrec ) { Path.OutPt op = outrec.getPoints(); do { op.idx = outrec.Idx; op = op.prev; } while (op != outrec.getPoints()); } private void updateWindingCount( Edge edge ) { LOGGER.entering( DefaultClipper.class.getName(), "updateWindingCount" ); Edge e = edge.prevInAEL; //find the edge of the same polytype that immediately preceeds 'edge' in AEL while (e != null && (e.polyTyp != edge.polyTyp || e.windDelta == 0)) { e = e.prevInAEL; } if (e == null) { edge.windCnt = edge.windDelta == 0 ? 1 : edge.windDelta; edge.windCnt2 = 0; e = activeEdges; //ie get ready to calc WindCnt2 } else if (edge.windDelta == 0 && clipType != ClipType.UNION) { edge.windCnt = 1; edge.windCnt2 = e.windCnt2; e = e.nextInAEL; //ie get ready to calc WindCnt2 } else if (edge.isEvenOddFillType( clipFillType, subjFillType )) { //EvenOdd filling ... if (edge.windDelta == 0) { //are we inside a subj polygon ... boolean Inside = true; Edge e2 = e.prevInAEL; while (e2 != null) { if (e2.polyTyp == e.polyTyp && e2.windDelta != 0) { Inside = !Inside; } e2 = e2.prevInAEL; } edge.windCnt = Inside ? 0 : 1; } else { edge.windCnt = edge.windDelta; } edge.windCnt2 = e.windCnt2; e = e.nextInAEL; //ie get ready to calc WindCnt2 } else { //nonZero, Positive or Negative filling ... if (e.windCnt * e.windDelta < 0) { //prev edge is 'decreasing' WindCount (WC) toward zero //so we're outside the previous polygon ... if (Math.abs( e.windCnt ) > 1) { //outside prev poly but still inside another. //when reversing direction of prev poly use the same WC if (e.windDelta * edge.windDelta < 0) { edge.windCnt = e.windCnt; } else { edge.windCnt = e.windCnt + edge.windDelta; } } else { //now outside all polys of same polytype so set own WC ... edge.windCnt = edge.windDelta == 0 ? 1 : edge.windDelta; } } else { //prev edge is 'increasing' WindCount (WC) away from zero //so we're inside the previous polygon ... if (edge.windDelta == 0) { edge.windCnt = e.windCnt < 0 ? e.windCnt - 1 : e.windCnt + 1; } else if (e.windDelta * edge.windDelta < 0) { edge.windCnt = e.windCnt; } else { edge.windCnt = e.windCnt + edge.windDelta; } } edge.windCnt2 = e.windCnt2; e = e.nextInAEL; //ie get ready to calc WindCnt2 } //update WindCnt2 ... if (edge.isEvenOddAltFillType( clipFillType, subjFillType )) { //EvenOdd filling ... while (e != edge) { if (e.windDelta != 0) { edge.windCnt2 = edge.windCnt2 == 0 ? 1 : 0; } e = e.nextInAEL; } } else { //nonZero, Positive or Negative filling ... while (e != edge) { edge.windCnt2 += e.windDelta; e = e.nextInAEL; } } } } //end Clipper
jieWang0/itextpdf
itext/src/main/java/com/itextpdf/text/pdf/parser/clipper/DefaultClipper.java
214,028
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package kr.dogfoot.hwplib.org.apache.poi.poifs.storage; /** * Abstract base class of all POIFS block storage classes. All * extensions of BigBlock should write 512 or 4096 bytes of data when * requested to write their data (as per their BigBlockSize). * * This class has package scope, as there is no reason at this time to * make the class public. * * @author Marc Johnson (mjohnson at apache dot org) */ import kr.dogfoot.hwplib.org.apache.poi.poifs.common.POIFSBigBlockSize; import kr.dogfoot.hwplib.org.apache.poi.poifs.common.POIFSConstants; import java.io.IOException; import java.io.OutputStream; abstract class BigBlock implements BlockWritable { /** * Either 512 bytes ({@link POIFSConstants#SMALLER_BIG_BLOCK_SIZE}) * or 4096 bytes ({@link POIFSConstants#LARGER_BIG_BLOCK_SIZE}) */ protected POIFSBigBlockSize bigBlockSize; protected BigBlock(POIFSBigBlockSize bigBlockSize) { this.bigBlockSize = bigBlockSize; } /** * Default implementation of write for extending classes that * contain their data in a simple array of bytes. * * @param stream the OutputStream to which the data should be * written. * @param data the byte array of to be written. * * @exception IOException on problems writing to the specified * stream. */ protected void doWriteData(final OutputStream stream, final byte [] data) throws IOException { stream.write(data); } /** * Write the block's data to an OutputStream * * @param stream the OutputStream to which the stored data should * be written * * @exception IOException on problems writing to the specified * stream */ abstract void writeData(final OutputStream stream) throws IOException; /* ********** START implementation of BlockWritable ********** */ /** * Write the storage to an OutputStream * * @param stream the OutputStream to which the stored data should * be written * * @exception IOException on problems writing to the specified * stream */ public void writeBlocks(final OutputStream stream) throws IOException { writeData(stream); } /* ********** END implementation of BlockWritable ********** */ } // end abstract class BigBlock
neolord0/hwplib
src/main/java/kr/dogfoot/hwplib/org/apache/poi/poifs/storage/BigBlock.java
214,029
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.SpringProperties; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** * Internal class that caches JavaBeans {@link PropertyDescriptor} * information for a Java class. Not intended for direct use by application code. * * <p>Necessary for own caching of descriptors within the application's * ClassLoader, rather than rely on the JDK's system-wide BeanInfo cache * (in order to avoid leaks on ClassLoader shutdown). * * <p>Information is cached statically, so we don't need to create new * objects of this class for every JavaBean we manipulate. Hence, this class * implements the factory design pattern, using a private constructor and * a static {@link #forClass(Class)} factory method to obtain instances. * * <p>Note that for caching to work effectively, some preconditions need to be met: * Prefer an arrangement where the Spring jars live in the same ClassLoader as the * application classes, which allows for clean caching along with the application's * lifecycle in any case. For a web application, consider declaring a local * {@link org.springframework.web.util.IntrospectorCleanupListener} in {@code web.xml} * in case of a multi-ClassLoader layout, which will allow for effective caching as well. * * <p>In case of a non-clean ClassLoader arrangement without a cleanup listener having * been set up, this class will fall back to a weak-reference-based caching model that * recreates much-requested entries every time the garbage collector removed them. In * such a scenario, consider the {@link #IGNORE_BEANINFO_PROPERTY_NAME} system property. * * @author Rod Johnson * @author Juergen Hoeller * @since 05 May 2001 * @see #acceptClassLoader(ClassLoader) * @see #clearClassLoader(ClassLoader) * @see #forClass(Class) */ public class CachedIntrospectionResults { /** * System property that instructs Spring to use the {@link Introspector#IGNORE_ALL_BEANINFO} * mode when calling the JavaBeans {@link Introspector}: "spring.beaninfo.ignore", with a * value of "true" skipping the search for {@code BeanInfo} classes (typically for scenarios * where no such classes are being defined for beans in the application in the first place). * <p>The default is "false", considering all {@code BeanInfo} metadata classes, like for * standard {@link Introspector#getBeanInfo(Class)} calls. Consider switching this flag to * "true" if you experience repeated ClassLoader access for non-existing {@code BeanInfo} * classes, in case such access is expensive on startup or on lazy loading. * <p>Note that such an effect may also indicate a scenario where caching doesn't work * effectively: Prefer an arrangement where the Spring jars live in the same ClassLoader * as the application classes, which allows for clean caching along with the application's * lifecycle in any case. For a web application, consider declaring a local * {@link org.springframework.web.util.IntrospectorCleanupListener} in {@code web.xml} * in case of a multi-ClassLoader layout, which will allow for effective caching as well. * @see Introspector#getBeanInfo(Class, int) */ public static final String IGNORE_BEANINFO_PROPERTY_NAME = "spring.beaninfo.ignore"; private static final boolean shouldIntrospectorIgnoreBeaninfoClasses = SpringProperties.getFlag(IGNORE_BEANINFO_PROPERTY_NAME); /** Stores the BeanInfoFactory instances */ private static List<BeanInfoFactory> beanInfoFactories = SpringFactoriesLoader.loadFactories( BeanInfoFactory.class, CachedIntrospectionResults.class.getClassLoader()); private static final Log logger = LogFactory.getLog(CachedIntrospectionResults.class); /** * Set of ClassLoaders that this CachedIntrospectionResults class will always * accept classes from, even if the classes do not qualify as cache-safe. */ static final Set<ClassLoader> acceptedClassLoaders = new HashSet<ClassLoader>(); /** * Map keyed by class containing CachedIntrospectionResults. * Needs to be a WeakHashMap with WeakReferences as values to allow * for proper garbage collection in case of multiple class loaders. */ static final Map<Class<?>, Object> classCache = new WeakHashMap<Class<?>, Object>(); /** * Accept the given ClassLoader as cache-safe, even if its classes would * not qualify as cache-safe in this CachedIntrospectionResults class. * <p>This configuration method is only relevant in scenarios where the Spring * classes reside in a 'common' ClassLoader (e.g. the system ClassLoader) * whose lifecycle is not coupled to the application. In such a scenario, * CachedIntrospectionResults would by default not cache any of the application's * classes, since they would create a leak in the common ClassLoader. * <p>Any {@code acceptClassLoader} call at application startup should * be paired with a {@link #clearClassLoader} call at application shutdown. * @param classLoader the ClassLoader to accept */ public static void acceptClassLoader(ClassLoader classLoader) { if (classLoader != null) { synchronized (acceptedClassLoaders) { acceptedClassLoaders.add(classLoader); } } } /** * Clear the introspection cache for the given ClassLoader, removing the * introspection results for all classes underneath that ClassLoader, and * removing the ClassLoader (and its children) from the acceptance list. * @param classLoader the ClassLoader to clear the cache for */ public static void clearClassLoader(ClassLoader classLoader) { synchronized (classCache) { for (Iterator<Class<?>> it = classCache.keySet().iterator(); it.hasNext();) { Class<?> beanClass = it.next(); if (isUnderneathClassLoader(beanClass.getClassLoader(), classLoader)) { it.remove(); } } } synchronized (acceptedClassLoaders) { for (Iterator<ClassLoader> it = acceptedClassLoaders.iterator(); it.hasNext();) { ClassLoader registeredLoader = it.next(); if (isUnderneathClassLoader(registeredLoader, classLoader)) { it.remove(); } } } } /** * Create CachedIntrospectionResults for the given bean class. * @param beanClass the bean class to analyze * @return the corresponding CachedIntrospectionResults * @throws BeansException in case of introspection failure */ @SuppressWarnings("unchecked") static CachedIntrospectionResults forClass(Class<?> beanClass) throws BeansException { CachedIntrospectionResults results; Object value; synchronized (classCache) { value = classCache.get(beanClass); } if (value instanceof Reference) { Reference<CachedIntrospectionResults> ref = (Reference<CachedIntrospectionResults>) value; results = ref.get(); } else { results = (CachedIntrospectionResults) value; } if (results == null) { if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader()) || isClassLoaderAccepted(beanClass.getClassLoader())) { results = new CachedIntrospectionResults(beanClass); synchronized (classCache) { classCache.put(beanClass, results); } } else { if (logger.isDebugEnabled()) { logger.debug("Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe"); } results = new CachedIntrospectionResults(beanClass); synchronized (classCache) { classCache.put(beanClass, new WeakReference<CachedIntrospectionResults>(results)); } } } return results; } /** * Check whether this CachedIntrospectionResults class is configured * to accept the given ClassLoader. * @param classLoader the ClassLoader to check * @return whether the given ClassLoader is accepted * @see #acceptClassLoader */ private static boolean isClassLoaderAccepted(ClassLoader classLoader) { // Iterate over array copy in order to avoid synchronization for the entire // ClassLoader check (avoiding a synchronized acceptedClassLoaders Iterator). ClassLoader[] acceptedLoaderArray; synchronized (acceptedClassLoaders) { acceptedLoaderArray = acceptedClassLoaders.toArray(new ClassLoader[acceptedClassLoaders.size()]); } for (ClassLoader acceptedLoader : acceptedLoaderArray) { if (isUnderneathClassLoader(classLoader, acceptedLoader)) { return true; } } return false; } /** * Check whether the given ClassLoader is underneath the given parent, * that is, whether the parent is within the candidate's hierarchy. * @param candidate the candidate ClassLoader to check * @param parent the parent ClassLoader to check for */ private static boolean isUnderneathClassLoader(ClassLoader candidate, ClassLoader parent) { if (candidate == parent) { return true; } if (candidate == null) { return false; } ClassLoader classLoaderToCheck = candidate; while (classLoaderToCheck != null) { classLoaderToCheck = classLoaderToCheck.getParent(); if (classLoaderToCheck == parent) { return true; } } return false; } /** The BeanInfo object for the introspected bean class */ private final BeanInfo beanInfo; /** PropertyDescriptor objects keyed by property name String */ private final Map<String, PropertyDescriptor> propertyDescriptorCache; /** TypeDescriptor objects keyed by PropertyDescriptor */ private final Map<PropertyDescriptor, TypeDescriptor> typeDescriptorCache; /** * Create a new CachedIntrospectionResults instance for the given class. * @param beanClass the bean class to analyze * @throws BeansException in case of introspection failure */ private CachedIntrospectionResults(Class<?> beanClass) throws BeansException { try { if (logger.isTraceEnabled()) { logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]"); } BeanInfo beanInfo = null; for (BeanInfoFactory beanInfoFactory : beanInfoFactories) { beanInfo = beanInfoFactory.getBeanInfo(beanClass); if (beanInfo != null) { break; } } if (beanInfo == null) { // If none of the factories supported the class, fall back to the default beanInfo = (shouldIntrospectorIgnoreBeaninfoClasses ? Introspector.getBeanInfo(beanClass, Introspector.IGNORE_ALL_BEANINFO) : Introspector.getBeanInfo(beanClass)); } this.beanInfo = beanInfo; if (logger.isTraceEnabled()) { logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]"); } this.propertyDescriptorCache = new LinkedHashMap<String, PropertyDescriptor>(); // This call is slow so we do it once. PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (Class.class.equals(beanClass) && ("classLoader".equals(pd.getName()) || "protectionDomain".equals(pd.getName()))) { // Ignore Class.getClassLoader() and getProtectionDomain() methods - nobody needs to bind to those continue; } if (logger.isTraceEnabled()) { logger.trace("Found bean property '" + pd.getName() + "'" + (pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]" : "") + (pd.getPropertyEditorClass() != null ? "; editor [" + pd.getPropertyEditorClass().getName() + "]" : "")); } pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd); this.propertyDescriptorCache.put(pd.getName(), pd); } this.typeDescriptorCache = new ConcurrentHashMap<PropertyDescriptor, TypeDescriptor>(); } catch (IntrospectionException ex) { throw new FatalBeanException("Failed to obtain BeanInfo for class [" + beanClass.getName() + "]", ex); } } BeanInfo getBeanInfo() { return this.beanInfo; } Class<?> getBeanClass() { return this.beanInfo.getBeanDescriptor().getBeanClass(); } PropertyDescriptor getPropertyDescriptor(String name) { PropertyDescriptor pd = this.propertyDescriptorCache.get(name); if (pd == null && StringUtils.hasLength(name)) { // Same lenient fallback checking as in PropertyTypeDescriptor... pd = this.propertyDescriptorCache.get(name.substring(0, 1).toLowerCase() + name.substring(1)); if (pd == null) { pd = this.propertyDescriptorCache.get(name.substring(0, 1).toUpperCase() + name.substring(1)); } } return (pd == null || pd instanceof GenericTypeAwarePropertyDescriptor ? pd : buildGenericTypeAwarePropertyDescriptor(getBeanClass(), pd)); } PropertyDescriptor[] getPropertyDescriptors() { PropertyDescriptor[] pds = new PropertyDescriptor[this.propertyDescriptorCache.size()]; int i = 0; for (PropertyDescriptor pd : this.propertyDescriptorCache.values()) { pds[i] = (pd instanceof GenericTypeAwarePropertyDescriptor ? pd : buildGenericTypeAwarePropertyDescriptor(getBeanClass(), pd)); i++; } return pds; } private PropertyDescriptor buildGenericTypeAwarePropertyDescriptor(Class<?> beanClass, PropertyDescriptor pd) { try { return new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(), pd.getWriteMethod(), pd.getPropertyEditorClass()); } catch (IntrospectionException ex) { throw new FatalBeanException("Failed to re-introspect class [" + beanClass.getName() + "]", ex); } } void addTypeDescriptor(PropertyDescriptor pd, TypeDescriptor td) { this.typeDescriptorCache.put(pd, td); } TypeDescriptor getTypeDescriptor(PropertyDescriptor pd) { return this.typeDescriptorCache.get(pd); } }
jinchihe/blog_demos
springbeans_modify/src/main/java/org/springframework/beans/CachedIntrospectionResults.java
214,030
/** * Copyright 2010 Richard Johnson & Orin Eman * * 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. * * --- * * This file is part of java-libpst. * * java-libpst 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. * * java-libpst 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 java-libpst. If not, see <http://www.gnu.org/licenses/>. * */ package com.pff; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Vector; /** * Represents a folder in the PST File * Allows you to access child folders or items. Items are accessed through a * sort of cursor arrangement. * This allows for incremental reading of a folder which may have _lots_ of * emails. * * @author Richard Johnson */ public class PSTFolder extends PSTObject { /** * a constructor for the rest of us... * * @param theFile * @param descriptorIndexNode * @throws PSTException * @throws IOException */ PSTFolder(final PSTFile theFile, final DescriptorIndexNode descriptorIndexNode) throws PSTException, IOException { super(theFile, descriptorIndexNode); } /** * For pre-populating a folder object with values. * Not recommended for use outside this library * * @param theFile * @param folderIndexNode * @param table */ PSTFolder(final PSTFile theFile, final DescriptorIndexNode folderIndexNode, final PSTTableBC table, final HashMap<Integer, PSTDescriptorItem> localDescriptorItems) { super(theFile, folderIndexNode, table, localDescriptorItems); } /** * get all of the sub folders... * there are not usually thousands, so we just do it in one big operation. * * @return all of the subfolders * @throws PSTException * @throws IOException */ public Vector<PSTFolder> getSubFolders() throws PSTException, IOException { final Vector<PSTFolder> output = new Vector<>(); try { this.initSubfoldersTable(); final List<HashMap<Integer, PSTTable7CItem>> itemMapSet = this.subfoldersTable.getItems(); for (final HashMap<Integer, PSTTable7CItem> itemMap : itemMapSet) { final PSTTable7CItem item = itemMap.get(26610); final PSTFolder folder = (PSTFolder) PSTObject.detectAndLoadPSTObject(this.pstFile, item.entryValueReference); output.add(folder); } } catch (final PSTException err) { // hierarchy node doesn't exist: This is OK if child count is 0. // Seen with special search folders at the top of the hierarchy: // "8739 - SPAM Search Folder 2", "8739 - Content.Filter". // this.subfoldersTable may remain uninitialized (null) in that case. if (this.getContentCount() != 0) { if (err.getMessage().startsWith("Can't get child folders")) { throw err; } else { //err.printStackTrace(); throw new PSTException("Can't get child folders for folder " + this.getDisplayName() + "(" + this.getDescriptorNodeId() + ") child count: " + this.getContentCount() + " - " + err.toString(), err); } } } return output; } private void initSubfoldersTable() throws IOException, PSTException { if (this.subfoldersTable != null) { return; } final long folderDescriptorIndex = this.descriptorIndexNode.descriptorIdentifier + 11; try { final DescriptorIndexNode folderDescriptor = this.pstFile.getDescriptorIndexNode(folderDescriptorIndex); HashMap<Integer, PSTDescriptorItem> tmp = null; if (folderDescriptor.localDescriptorsOffsetIndexIdentifier > 0) { // tmp = new PSTDescriptor(pstFile, // folderDescriptor.localDescriptorsOffsetIndexIdentifier).getChildren(); tmp = this.pstFile.getPSTDescriptorItems(folderDescriptor.localDescriptorsOffsetIndexIdentifier); } this.subfoldersTable = new PSTTable7C(new PSTNodeInputStream(this.pstFile, this.pstFile.getOffsetIndexNode(folderDescriptor.dataOffsetIndexIdentifier)), tmp); } catch (final PSTException err) { // hierarchy node doesn't exist throw new PSTException("Can't get child folders for folder " + this.getDisplayName() + "(" + this.getDescriptorNodeId() + ") child count: " + this.getContentCount() + " - " + err.toString(), err); } } /** * internal vars for the tracking of things.. */ private int currentEmailIndex = 0; private final LinkedHashSet<DescriptorIndexNode> otherItems = null; private PSTTable7C emailsTable = null; private LinkedList<DescriptorIndexNode> fallbackEmailsTable = null; private PSTTable7C subfoldersTable = null; /** * this method goes through all of the children and sorts them into one of * the three hash sets. * * @throws PSTException * @throws IOException */ private void initEmailsTable() throws PSTException, IOException { if (this.emailsTable != null || this.fallbackEmailsTable != null) { return; } // some folder types don't have children: if (this.getNodeType() == PSTObject.NID_TYPE_SEARCH_FOLDER) { return; } try { final long folderDescriptorIndex = this.descriptorIndexNode.descriptorIdentifier + 12; // +12 // lists // emails! // :D final DescriptorIndexNode folderDescriptor = this.pstFile.getDescriptorIndexNode(folderDescriptorIndex); HashMap<Integer, PSTDescriptorItem> tmp = null; if (folderDescriptor.localDescriptorsOffsetIndexIdentifier > 0) { // tmp = new PSTDescriptor(pstFile, // folderDescriptor.localDescriptorsOffsetIndexIdentifier).getChildren(); tmp = this.pstFile.getPSTDescriptorItems(folderDescriptor.localDescriptorsOffsetIndexIdentifier); } // PSTTable7CForFolder folderDescriptorTable = new // PSTTable7CForFolder(folderDescriptor.dataBlock.data, // folderDescriptor.dataBlock.blockOffsets,tmp, 0x67F2); this.emailsTable = new PSTTable7C(new PSTNodeInputStream(this.pstFile, this.pstFile.getOffsetIndexNode(folderDescriptor.dataOffsetIndexIdentifier)), tmp, 0x67F2); } catch (final Exception err) { // here we have to attempt to fallback onto the children as listed // by the descriptor b-tree final LinkedHashMap<Integer, LinkedList<DescriptorIndexNode>> tree = this.pstFile.getChildDescriptorTree(); this.fallbackEmailsTable = new LinkedList<>(); final LinkedList<DescriptorIndexNode> allChildren = tree.get(this.getDescriptorNode().descriptorIdentifier); if (allChildren != null) { // quickly go through and remove those entries that are not // messages! for (final DescriptorIndexNode node : allChildren) { if (node != null && PSTObject.getNodeType(node.descriptorIdentifier) == PSTObject.NID_TYPE_NORMAL_MESSAGE) { this.fallbackEmailsTable.add(node); } } } System.err.println("Can't get children for folder " + this.getDisplayName() + "(" + this.getDescriptorNodeId() + ") child count: " + this.getContentCount() + " - " + err.toString() + ", using alternate child tree with " + this.fallbackEmailsTable.size() + " items"); } } /** * get some children from the folder * This is implemented as a cursor of sorts, as there could be thousands * and that is just too many to process at once. * * @param numberToReturn * @return bunch of children in this folder * @throws PSTException * @throws IOException */ public Vector<PSTObject> getChildren(final int numberToReturn) throws PSTException, IOException { this.initEmailsTable(); final Vector<PSTObject> output = new Vector<>(); if (this.emailsTable != null) { final List<HashMap<Integer, PSTTable7CItem>> rows = this.emailsTable.getItems(this.currentEmailIndex, numberToReturn); for (int x = 0; x < rows.size(); x++) { if (this.currentEmailIndex >= this.getContentCount()) { // no more! break; } // get the emails from the rows final PSTTable7CItem emailRow = rows.get(x).get(0x67F2); final DescriptorIndexNode childDescriptor = this.pstFile .getDescriptorIndexNode(emailRow.entryValueReference); final PSTObject child = PSTObject.detectAndLoadPSTObject(this.pstFile, childDescriptor); output.add(child); this.currentEmailIndex++; } } else if (this.fallbackEmailsTable != null) { // we use the fallback final ListIterator<DescriptorIndexNode> iterator = this.fallbackEmailsTable .listIterator(this.currentEmailIndex); for (int x = 0; x < numberToReturn; x++) { if (this.currentEmailIndex >= this.getContentCount()) { // no more! break; } final DescriptorIndexNode childDescriptor = iterator.next(); final PSTObject child = PSTObject.detectAndLoadPSTObject(this.pstFile, childDescriptor); output.add(child); this.currentEmailIndex++; } } return output; } public LinkedList<Integer> getChildDescriptorNodes() throws PSTException, IOException { this.initEmailsTable(); if (this.emailsTable == null) { return new LinkedList<>(); } final LinkedList<Integer> output = new LinkedList<>(); final List<HashMap<Integer, PSTTable7CItem>> rows = this.emailsTable.getItems(); for (final HashMap<Integer, PSTTable7CItem> row : rows) { // get the emails from the rows if (this.currentEmailIndex == this.getContentCount()) { // no more! break; } final PSTTable7CItem emailRow = row.get(0x67F2); if (emailRow.entryValueReference == 0) { break; } output.add(emailRow.entryValueReference); } return output; } /** * Get the next child of this folder * As there could be thousands of emails, we have these kind of cursor * operations * * @return the next email in the folder or null if at the end of the folder * @throws PSTException * @throws IOException */ public PSTObject getNextChild() throws PSTException, IOException { this.initEmailsTable(); if (this.emailsTable != null) { final List<HashMap<Integer, PSTTable7CItem>> rows = this.emailsTable.getItems(this.currentEmailIndex, 1); if (this.currentEmailIndex == this.getContentCount()) { // no more! return null; } // get the emails from the rows final PSTTable7CItem emailRow = rows.get(0).get(0x67F2); final DescriptorIndexNode childDescriptor = this.pstFile .getDescriptorIndexNode(emailRow.entryValueReference); final PSTObject child = PSTObject.detectAndLoadPSTObject(this.pstFile, childDescriptor); this.currentEmailIndex++; return child; } else if (this.fallbackEmailsTable != null) { if (this.currentEmailIndex >= this.getContentCount() || this.currentEmailIndex >= this.fallbackEmailsTable.size()) { // no more! return null; } // get the emails from the rows final DescriptorIndexNode childDescriptor = this.fallbackEmailsTable.get(this.currentEmailIndex); final PSTObject child = PSTObject.detectAndLoadPSTObject(this.pstFile, childDescriptor); this.currentEmailIndex++; return child; } return null; } /** * move the internal folder cursor to the desired position * position 0 is before the first record. * * @param newIndex */ public void moveChildCursorTo(int newIndex) throws IOException, PSTException { this.initEmailsTable(); if (newIndex < 1) { this.currentEmailIndex = 0; return; } if (newIndex > this.getContentCount()) { newIndex = this.getContentCount(); } this.currentEmailIndex = newIndex; } /** * the number of child folders in this folder * * @return number of subfolders as counted * @throws IOException * @throws PSTException */ public int getSubFolderCount() throws IOException, PSTException { this.initSubfoldersTable(); if (this.subfoldersTable != null) { return this.subfoldersTable.getRowCount(); } else { return 0; } } /** * the number of emails in this folder * this is the count of emails made by the library and will therefore should * be more accurate than getContentCount * * @return number of emails in this folder (as counted) * @throws IOException * @throws PSTException */ public int getEmailCount() throws IOException, PSTException { this.initEmailsTable(); if (this.emailsTable == null) { return -1; } return this.emailsTable.getRowCount(); } public int getFolderType() { return this.getIntItem(0x3601); } /** * the number of emails in this folder * this is as reported by the PST file, for a number calculated by the * library use getEmailCount * * @return number of items as reported by PST File */ public int getContentCount() { return this.getIntItem(0x3602); } /** * Amount of unread content items Integer 32-bit signed */ public int getUnreadCount() { return this.getIntItem(0x3603); } /** * does this folder have subfolders * once again, read from the PST, use getSubFolderCount if you want to know * what the library makes of it all * * @return has subfolders as reported by the PST File */ public boolean hasSubfolders() { return (this.getIntItem(0x360a) != 0); } public String getContainerClass() { return this.getStringItem(0x3613); } public int getAssociateContentCount() { return this.getIntItem(0x3617); } /** * Container flags Integer 32-bit signed */ public int getContainerFlags() { return this.getIntItem(0x3600); } } // vim: set noexpandtab:
rjohnsondev/java-libpst
src/main/java/com/pff/PSTFolder.java
214,031
/* * Copyright 1999,2004 The Apache Software Foundation. * * 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. * * Created for feature LIDB4147-9 "Integrate Unified Expression Language" 2006/08/14 Scott Johnson * Modified for jsp2.1ELwork */ package org.apache.jasper.compiler; /** * This class implements a parser for EL expressions. * * It takes strings of the form xxx${..}yyy${..}zzz etc, and turn it into a * ELNode.Nodes. * * Currently, it only handles text outside ${..} and functions in ${ ..}. * * @author Kin-man Chung */ public class ELParser { private Token curToken; // current token private ELNode.Nodes expr; private ELNode.Nodes ELexpr; private int index; // Current index of the expression private String expression; // The EL expression private char type; private boolean escapeBS; // is '\' an escape char in text outside EL? private static final String reservedWords[] = { "and", "div", "empty", "eq", "false", "ge", "gt", "instanceof", "le", "lt", "mod", "ne", "not", "null", "or", "true" }; public ELParser(String expression) { index = 0; this.expression = expression; expr = new ELNode.Nodes(); } /** * Parse an EL expression * * @param expression * The input expression string of the form Char* ('${' Char* * '}')* Char* * @return Parsed EL expression in ELNode.Nodes */ public static ELNode.Nodes parse(String expression) { ELParser parser = new ELParser(expression); while (parser.hasNextChar()) { String text = parser.skipUntilEL(); if (text.length() > 0) { parser.expr.add(new ELNode.Text(text)); } ELNode.Nodes elexpr = parser.parseEL(); if (!elexpr.isEmpty()) { parser.expr.add(new ELNode.Root(elexpr, parser.type)); } } return parser.expr; } /** * Parse an EL expression string '${...}' * * @return An ELNode.Nodes representing the EL expression TODO: Currently * only parsed into functions and text strings. This should be * rewritten for a full parser. */ private ELNode.Nodes parseEL() { StringBuffer buf = new StringBuffer(); ELexpr = new ELNode.Nodes(); while (hasNext()) { curToken = nextToken(); if (curToken instanceof Char) { if (curToken.toChar() == '}') { break; } buf.append(curToken.toChar()); } else { // Output whatever is in buffer if (buf.length() > 0) { ELexpr.add(new ELNode.ELText(buf.toString())); } if (!parseFunction()) { ELexpr.add(new ELNode.ELText(curToken.toString())); } } } if (buf.length() > 0) { ELexpr.add(new ELNode.ELText(buf.toString())); } return ELexpr; } /** * Parse for a function FunctionInvokation ::= (identifier ':')? identifier * '(' (Expression (,Expression)*)? ')' Note: currently we don't parse * arguments */ private boolean parseFunction() { if (!(curToken instanceof Id) || isELReserved(curToken.toString())) { return false; } String s1 = null; // Function prefix String s2 = curToken.toString(); // Function name int mark = getIndex(); if (hasNext()) { Token t = nextToken(); if (t.toChar() == ':') { if (hasNext()) { Token t2 = nextToken(); if (t2 instanceof Id) { s1 = s2; s2 = t2.toString(); if (hasNext()) { t = nextToken(); } } } } if (t.toChar() == '(') { ELexpr.add(new ELNode.Function(s1, s2)); return true; } } setIndex(mark); return false; } /** * Test if an id is a reserved word in EL */ private boolean isELReserved(String id) { int i = 0; int j = reservedWords.length; while (i < j) { int k = (i + j) / 2; int result = reservedWords[k].compareTo(id); if (result == 0) { return true; } if (result < 0) { i = k + 1; } else { j = k; } } return false; } /** * Skip until an EL expression ('${' || '#{') is reached, allowing escape * sequences '\\' and '\$' and '\#'. * * @return The text string up to the EL expression */ private String skipUntilEL() { char prev = 0; StringBuffer buf = new StringBuffer(); while (hasNextChar()) { char ch = nextChar(); if (prev == '\\') { prev = 0; if (ch == '\\') { buf.append('\\'); if (!escapeBS) prev = '\\'; } else if (ch == '$' || ch == '#') { buf.append(ch); } // else error! } else if (prev == '$' || prev == '#') { if (ch == '{') { this.type = prev; prev = 0; break; } buf.append(prev); prev = 0; } if (ch == '\\' || ch == '$' || ch == '#') { prev = ch; } else { buf.append(ch); } } if (prev != 0) { buf.append(prev); } return buf.toString(); } /* * @return true if there is something left in EL expression buffer other * than white spaces. */ private boolean hasNext() { skipSpaces(); return hasNextChar(); } /* * @return The next token in the EL expression buffer. */ private Token nextToken() { skipSpaces(); if (hasNextChar()) { char ch = nextChar(); if (Character.isJavaIdentifierStart(ch)) { StringBuffer buf = new StringBuffer(); buf.append(ch); while ((ch = peekChar()) != -1 && Character.isJavaIdentifierPart(ch)) { buf.append(ch); nextChar(); } return new Id(buf.toString()); } if (ch == '\'' || ch == '"') { return parseQuotedChars(ch); } else { // For now... return new Char(ch); } } return null; } /* * Parse a string in single or double quotes, allowing for escape sequences * '\\', and ('\"', or "\'") */ private Token parseQuotedChars(char quote) { StringBuffer buf = new StringBuffer(); buf.append(quote); while (hasNextChar()) { char ch = nextChar(); if (ch == '\\') { ch = nextChar(); if (ch == '\\' || ch == quote) { buf.append(ch); } // else error! } else if (ch == quote) { buf.append(ch); break; } else { buf.append(ch); } } return new QuotedString(buf.toString()); } /* * A collection of low level parse methods dealing with character in the EL * expression buffer. */ private void skipSpaces() { while (hasNextChar()) { if (expression.charAt(index) > ' ') break; index++; } } private boolean hasNextChar() { return index < expression.length(); } private char nextChar() { if (index >= expression.length()) { return (char) -1; } return expression.charAt(index++); } private char peekChar() { if (index >= expression.length()) { return (char) -1; } return expression.charAt(index); } private int getIndex() { return index; } private void setIndex(int i) { index = i; } /* * Represents a token in EL expression string */ private static class Token { char toChar() { return 0; } public String toString() { return ""; } } /* * Represents an ID token in EL */ private static class Id extends Token { String id; Id(String id) { this.id = id; } public String toString() { return id; } } /* * Represents a character token in EL */ private static class Char extends Token { private char ch; Char(char ch) { this.ch = ch; } char toChar() { return ch; } public String toString() { return (new Character(ch)).toString(); } } /* * Represents a quoted (single or double) string token in EL */ private static class QuotedString extends Token { private String value; QuotedString(String v) { this.value = v; } public String toString() { return value; } } public char getType() { return type; } }
tjwatson/open-liberty
dev/com.ibm.ws.jsp/src/org/apache/jasper/compiler/ELParser.java
214,032
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.propertyeditors; import java.beans.PropertyEditorSupport; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Custom {@link java.beans.PropertyEditor} for String arrays. * * <p>Strings must be in CSV format, with a customizable separator. * By default values in the result are trimmed of whitespace. * * @author Rod Johnson * @author Juergen Hoeller * @author Dave Syer * @see StringUtils#delimitedListToStringArray * @see StringUtils#arrayToDelimitedString */ public class StringArrayPropertyEditor extends PropertyEditorSupport { /** * Default separator for splitting a String: a comma (",") */ public static final String DEFAULT_SEPARATOR = ","; private final String separator; private final String charsToDelete; private final boolean emptyArrayAsNull; private final boolean trimValues; /** * Create a new StringArrayPropertyEditor with the default separator * (a comma). * <p>An empty text (without elements) will be turned into an empty array. */ public StringArrayPropertyEditor() { this(DEFAULT_SEPARATOR, null, false); } /** * Create a new StringArrayPropertyEditor with the given separator. * <p>An empty text (without elements) will be turned into an empty array. * @param separator the separator to use for splitting a {@link String} */ public StringArrayPropertyEditor(String separator) { this(separator, null, false); } /** * Create a new StringArrayPropertyEditor with the given separator. * @param separator the separator to use for splitting a {@link String} * @param emptyArrayAsNull {@code true} if an empty String array * is to be transformed into {@code null} */ public StringArrayPropertyEditor(String separator, boolean emptyArrayAsNull) { this(separator, null, emptyArrayAsNull); } /** * Create a new StringArrayPropertyEditor with the given separator. * @param separator the separator to use for splitting a {@link String} * @param emptyArrayAsNull {@code true} if an empty String array * is to be transformed into {@code null} * @param trimValues {@code true} if the values in the parsed arrays * are to be be trimmed of whitespace (default is true). */ public StringArrayPropertyEditor(String separator, boolean emptyArrayAsNull, boolean trimValues) { this(separator, null, emptyArrayAsNull, trimValues); } /** * Create a new StringArrayPropertyEditor with the given separator. * @param separator the separator to use for splitting a {@link String} * @param charsToDelete a set of characters to delete, in addition to * trimming an input String. Useful for deleting unwanted line breaks: * e.g. "\r\n\f" will delete all new lines and line feeds in a String. * @param emptyArrayAsNull {@code true} if an empty String array * is to be transformed into {@code null} */ public StringArrayPropertyEditor(String separator, String charsToDelete, boolean emptyArrayAsNull) { this(separator, charsToDelete, emptyArrayAsNull, true); } /** * Create a new StringArrayPropertyEditor with the given separator. * @param separator the separator to use for splitting a {@link String} * @param charsToDelete a set of characters to delete, in addition to * trimming an input String. Useful for deleting unwanted line breaks: * e.g. "\r\n\f" will delete all new lines and line feeds in a String. * @param emptyArrayAsNull {@code true} if an empty String array * is to be transformed into {@code null} * @param trimValues {@code true} if the values in the parsed arrays * are to be be trimmed of whitespace (default is true). */ public StringArrayPropertyEditor(String separator, String charsToDelete, boolean emptyArrayAsNull, boolean trimValues) { this.separator = separator; this.charsToDelete = charsToDelete; this.emptyArrayAsNull = emptyArrayAsNull; this.trimValues = trimValues; } @Override public void setAsText(String text) throws IllegalArgumentException { String[] array = StringUtils.delimitedListToStringArray(text, this.separator, this.charsToDelete); if (trimValues) { array = StringUtils.trimArrayElements(array); } if (this.emptyArrayAsNull && array.length == 0) { setValue(null); } else { setValue(array); } } @Override public String getAsText() { return StringUtils.arrayToDelimitedString(ObjectUtils.toObjectArray(getValue()), this.separator); } }
jinchihe/blog_demos
springbeans_modify/src/main/java/org/springframework/beans/propertyeditors/StringArrayPropertyEditor.java
214,033
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.erudika.scoold.velocity; import org.apache.velocity.app.VelocityEngine; /** * Interface to be implemented by objects that configure and manage a * VelocityEngine for automatic lookup in a web environment. Detected * and used by VelocityView. * * @author Rod Johnson * @see VelocityConfigurer * @see VelocityView */ public interface VelocityConfig { /** * Return the VelocityEngine for the current web application context. * May be unique to one servlet, or shared in the root context. * @return the VelocityEngine */ VelocityEngine getVelocityEngine(); }
epasham/scoold
src/main/java/com/erudika/scoold/velocity/VelocityConfig.java
214,034
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.concurrent.locks; import java.util.Objects; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.StampedLock; import java.util.function.Supplier; import org.apache.commons.lang3.function.Failable; import org.apache.commons.lang3.function.FailableConsumer; import org.apache.commons.lang3.function.FailableFunction; import org.apache.commons.lang3.function.Suppliers; /** * Combines the monitor and visitor pattern to work with {@link java.util.concurrent.locks.Lock locked objects}. Locked * objects are an alternative to synchronization. This, on Wikipedia, is known as the Visitor pattern * (https://en.wikipedia.org/wiki/Visitor_pattern), and from the "Gang of Four" "Design Patterns" book's Visitor pattern * [Gamma, E., Helm, R., &amp; Johnson, R. (1998). Visitor. In Design patterns elements of reusable object oriented software (pp. 331-344). Reading: Addison Wesley.]. * * <p> * Locking is preferable, if there is a distinction between read access (multiple threads may have read access * concurrently), and write access (only one thread may have write access at any given time). In comparison, * synchronization doesn't support read access, because synchronized access is exclusive. * </p> * <p> * Using this class is fairly straightforward: * </p> * <ol> * <li>While still in single thread mode, create an instance of {@link LockingVisitors.StampedLockVisitor} by calling * {@link #stampedLockVisitor(Object)}, passing the object which needs to be locked. Discard all references to the * locked object. Instead, use references to the lock.</li> * <li>If you want to access the locked object, create a {@link FailableConsumer}. The consumer will receive the locked * object as a parameter. For convenience, the consumer may be implemented as a Lambda. Then invoke * {@link LockingVisitors.StampedLockVisitor#acceptReadLocked(FailableConsumer)}, or * {@link LockingVisitors.StampedLockVisitor#acceptWriteLocked(FailableConsumer)}, passing the consumer.</li> * <li>As an alternative, if you need to produce a result object, you may use a {@link FailableFunction}. This function * may also be implemented as a Lambda. To have the function executed, invoke * {@link LockingVisitors.StampedLockVisitor#applyReadLocked(FailableFunction)}, or * {@link LockingVisitors.StampedLockVisitor#applyWriteLocked(FailableFunction)}.</li> * </ol> * <p> * Example: A thread safe logger class. * </p> * * <pre> * public class SimpleLogger { * * private final StampedLockVisitor&lt;PrintStream&gt; lock; * * public SimpleLogger(OutputStream out) { * lock = LockingVisitors.stampedLockVisitor(new PrintStream(out)); * } * * public void log(String message) { * lock.acceptWriteLocked((ps) -&gt; ps.println(message)); * } * * public void log(byte[] buffer) { * lock.acceptWriteLocked((ps) -&gt; { ps.write(buffer); ps.println(); }); * } * </pre> * * @since 3.11 */ public class LockingVisitors { /** * Wraps a domain object and a lock for access by lambdas. * * @param <O> the wrapped object type. * @param <L> the wrapped lock type. */ public static class LockVisitor<O, L> { /** * The lock object, untyped, since, for example {@link StampedLock} does not implement a locking interface in * Java 8. */ private final L lock; /** * The guarded object. */ private final O object; /** * Supplies the read lock, usually from the lock object. */ private final Supplier<Lock> readLockSupplier; /** * Supplies the write lock, usually from the lock object. */ private final Supplier<Lock> writeLockSupplier; /** * Constructs an instance. * * @param object The object to guard. * @param lock The locking object. * @param readLockSupplier Supplies the read lock, usually from the lock object. * @param writeLockSupplier Supplies the write lock, usually from the lock object. */ protected LockVisitor(final O object, final L lock, final Supplier<Lock> readLockSupplier, final Supplier<Lock> writeLockSupplier) { this.object = Objects.requireNonNull(object, "object"); this.lock = Objects.requireNonNull(lock, "lock"); this.readLockSupplier = Objects.requireNonNull(readLockSupplier, "readLockSupplier"); this.writeLockSupplier = Objects.requireNonNull(writeLockSupplier, "writeLockSupplier"); } /** * Provides read (shared, non-exclusive) access to the locked (hidden) object. More precisely, what the method * will do (in the given order): * * <ol> * <li>Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a * lock is granted.</li> * <li>Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.</li> * <li>Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the * lock will be released anyways.</li> * </ol> * * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the * consumers parameter. * @see #acceptWriteLocked(FailableConsumer) * @see #applyReadLocked(FailableFunction) */ public void acceptReadLocked(final FailableConsumer<O, ?> consumer) { lockAcceptUnlock(readLockSupplier, consumer); } /** * Provides write (exclusive) access to the locked (hidden) object. More precisely, what the method will do (in * the given order): * * <ol> * <li>Obtain a write (shared) lock on the locked (hidden) object. The current thread may block, until such a * lock is granted.</li> * <li>Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.</li> * <li>Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the * lock will be released anyways.</li> * </ol> * * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the * consumers parameter. * @see #acceptReadLocked(FailableConsumer) * @see #applyWriteLocked(FailableFunction) */ public void acceptWriteLocked(final FailableConsumer<O, ?> consumer) { lockAcceptUnlock(writeLockSupplier, consumer); } /** * Provides read (shared, non-exclusive) access to the locked (hidden) object for the purpose of computing a * result object. More precisely, what the method will do (in the given order): * * <ol> * <li>Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a * lock is granted.</li> * <li>Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, * receiving the functions result.</li> * <li>Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the * lock will be released anyways.</li> * <li>Return the result object, that has been received from the functions invocation.</li> * </ol> * <p> * <em>Example:</em> Consider that the hidden object is a list, and we wish to know the current size of the * list. This might be achieved with the following: * </p> * <pre> * private Lock&lt;List&lt;Object&gt;&gt; listLock; * * public int getCurrentListSize() { * final Integer sizeInteger = listLock.applyReadLocked((list) -&gt; Integer.valueOf(list.size)); * return sizeInteger.intValue(); * } * </pre> * * @param <T> The result type (both the functions, and this method's.) * @param function The function, which is being invoked to compute the result. The function will receive the * hidden object. * @return The result object, which has been returned by the functions invocation. * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend * access to the hidden object beyond this methods lifetime and will therefore be prevented. * @see #acceptReadLocked(FailableConsumer) * @see #applyWriteLocked(FailableFunction) */ public <T> T applyReadLocked(final FailableFunction<O, T, ?> function) { return lockApplyUnlock(readLockSupplier, function); } /** * Provides write (exclusive) access to the locked (hidden) object for the purpose of computing a result object. * More precisely, what the method will do (in the given order): * * <ol> * <li>Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a * lock is granted.</li> * <li>Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, * receiving the functions result.</li> * <li>Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the * lock will be released anyways.</li> * <li>Return the result object, that has been received from the functions invocation.</li> * </ol> * * @param <T> The result type (both the functions, and this method's.) * @param function The function, which is being invoked to compute the result. The function will receive the * hidden object. * @return The result object, which has been returned by the functions invocation. * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend * access to the hidden object beyond this methods lifetime and will therefore be prevented. * @see #acceptReadLocked(FailableConsumer) * @see #applyWriteLocked(FailableFunction) */ public <T> T applyWriteLocked(final FailableFunction<O, T, ?> function) { return lockApplyUnlock(writeLockSupplier, function); } /** * Gets the lock. * * @return the lock. */ public L getLock() { return lock; } /** * Gets the guarded object. * * @return the object. */ public O getObject() { return object; } /** * This method provides the default implementation for {@link #acceptReadLocked(FailableConsumer)}, and * {@link #acceptWriteLocked(FailableConsumer)}. * * @param lockSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used * internally.) * @param consumer The consumer, which is to be given access to the locked (hidden) object, which will be passed * as a parameter. * @see #acceptReadLocked(FailableConsumer) * @see #acceptWriteLocked(FailableConsumer) */ protected void lockAcceptUnlock(final Supplier<Lock> lockSupplier, final FailableConsumer<O, ?> consumer) { final Lock lock = Objects.requireNonNull(Suppliers.get(lockSupplier), "lock"); lock.lock(); try { if (consumer != null) { consumer.accept(object); } } catch (final Throwable t) { throw Failable.rethrow(t); } finally { lock.unlock(); } } /** * This method provides the actual implementation for {@link #applyReadLocked(FailableFunction)}, and * {@link #applyWriteLocked(FailableFunction)}. * * @param <T> The result type (both the functions, and this method's.) * @param lockSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used * internally.) * @param function The function, which is being invoked to compute the result object. This function will receive * the locked (hidden) object as a parameter. * @return The result object, which has been returned by the functions invocation. * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend * access to the hidden object beyond this methods lifetime and will therefore be prevented. * @see #applyReadLocked(FailableFunction) * @see #applyWriteLocked(FailableFunction) */ protected <T> T lockApplyUnlock(final Supplier<Lock> lockSupplier, final FailableFunction<O, T, ?> function) { final Lock lock = Objects.requireNonNull(Suppliers.get(lockSupplier), "lock"); lock.lock(); try { return function.apply(object); } catch (final Throwable t) { throw Failable.rethrow(t); } finally { lock.unlock(); } } } /** * This class implements a wrapper for a locked (hidden) object, and provides the means to access it. The basic * idea, is that the user code forsakes all references to the locked object, using only the wrapper object, and the * accessor methods {@link #acceptReadLocked(FailableConsumer)}, {@link #acceptWriteLocked(FailableConsumer)}, * {@link #applyReadLocked(FailableFunction)}, and {@link #applyWriteLocked(FailableFunction)}. By doing so, the * necessary protections are guaranteed. * * @param <O> The locked (hidden) objects type. */ public static class ReadWriteLockVisitor<O> extends LockVisitor<O, ReadWriteLock> { /** * Creates a new instance with the given locked object. This constructor is supposed to be used for subclassing * only. In general, it is suggested to use {@link LockingVisitors#stampedLockVisitor(Object)} instead. * * @param object The locked (hidden) object. The caller is supposed to drop all references to the locked object. * @param readWriteLock the lock to use. */ protected ReadWriteLockVisitor(final O object, final ReadWriteLock readWriteLock) { super(object, readWriteLock, readWriteLock::readLock, readWriteLock::writeLock); } } /** * This class implements a wrapper for a locked (hidden) object, and provides the means to access it. The basic * idea is that the user code forsakes all references to the locked object, using only the wrapper object, and the * accessor methods {@link #acceptReadLocked(FailableConsumer)}, {@link #acceptWriteLocked(FailableConsumer)}, * {@link #applyReadLocked(FailableFunction)}, and {@link #applyWriteLocked(FailableFunction)}. By doing so, the * necessary protections are guaranteed. * * @param <O> The locked (hidden) objects type. */ public static class StampedLockVisitor<O> extends LockVisitor<O, StampedLock> { /** * Creates a new instance with the given locked object. This constructor is supposed to be used for subclassing * only. In general, it is suggested to use {@link LockingVisitors#stampedLockVisitor(Object)} instead. * * @param object The locked (hidden) object. The caller is supposed to drop all references to the locked object. * @param stampedLock the lock to use. */ protected StampedLockVisitor(final O object, final StampedLock stampedLock) { super(object, stampedLock, stampedLock::asReadLock, stampedLock::asWriteLock); } } /** * Creates a new instance of {@link ReadWriteLockVisitor} with the given (hidden) object and lock. * * @param <O> The locked objects type. * @param object The locked (hidden) object. * @param readWriteLock The lock to use. * @return The created instance, a {@link StampedLockVisitor lock} for the given object. * @since 3.13.0 */ public static <O> ReadWriteLockVisitor<O> create(final O object, final ReadWriteLock readWriteLock) { return new LockingVisitors.ReadWriteLockVisitor<>(object, readWriteLock); } /** * Creates a new instance of {@link ReadWriteLockVisitor} with the given (hidden) object. * * @param <O> The locked objects type. * @param object The locked (hidden) object. * @return The created instance, a {@link StampedLockVisitor lock} for the given object. */ public static <O> ReadWriteLockVisitor<O> reentrantReadWriteLockVisitor(final O object) { return create(object, new ReentrantReadWriteLock()); } /** * Creates a new instance of {@link StampedLockVisitor} with the given (hidden) object. * * @param <O> The locked objects type. * @param object The locked (hidden) object. * @return The created instance, a {@link StampedLockVisitor lock} for the given object. */ public static <O> StampedLockVisitor<O> stampedLockVisitor(final O object) { return new LockingVisitors.StampedLockVisitor<>(object, new StampedLock()); } /** * Make private in 4.0. * * @deprecated TODO Make private in 4.0. */ @Deprecated public LockingVisitors() { // empty } }
apache/commons-lang
src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java
214,035
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package kr.dogfoot.hwplib.org.apache.poi.poifs.storage; import kr.dogfoot.hwplib.org.apache.poi.poifs.common.POIFSBigBlockSize; import kr.dogfoot.hwplib.org.apache.poi.poifs.common.POIFSConstants; import kr.dogfoot.hwplib.org.apache.poi.util.LittleEndian; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; /** * A block of block allocation table entries. BATBlocks are created * only through a static factory method: createBATBlocks. * * @author Marc Johnson (mjohnson at apache dot org) */ public final class BATBlock extends BigBlock { /** * For a regular fat block, these are 128 / 1024 * next sector values. * For a XFat (DIFat) block, these are 127 / 1023 * next sector values, then a chaining value. */ private int[] _values; /** * Does this BATBlock have any free sectors in it? */ private boolean _has_free_sectors; /** * Where in the file are we? */ private int ourBlockIndex; /** * Create a single instance initialized with default values */ private BATBlock(POIFSBigBlockSize bigBlockSize) { super(bigBlockSize); int _entries_per_block = bigBlockSize.getBATEntriesPerBlock(); _values = new int[_entries_per_block]; _has_free_sectors = true; Arrays.fill(_values, POIFSConstants.UNUSED_BLOCK); } /** * Create a single instance initialized (perhaps partially) with entries * * @param entries the array of block allocation table entries * @param start_index the index of the first entry to be written * to the block * @param end_index the index, plus one, of the last entry to be * written to the block (writing is for all index * k, start_index <= k < end_index) */ private BATBlock(POIFSBigBlockSize bigBlockSize, final int [] entries, final int start_index, final int end_index) { this(bigBlockSize); for (int k = start_index; k < end_index; k++) { _values[k - start_index] = entries[k]; } // Do we have any free sectors? if(end_index - start_index == _values.length) { recomputeFree(); } } private void recomputeFree() { boolean hasFree = false; for(int k=0; k<_values.length; k++) { if(_values[k] == POIFSConstants.UNUSED_BLOCK) { hasFree = true; break; } } _has_free_sectors = hasFree; } /** * Create a single BATBlock from the byte buffer, which must hold at least * one big block of data to be read. */ public static BATBlock createBATBlock(final POIFSBigBlockSize bigBlockSize, ByteBuffer data) { // Create an empty block BATBlock block = new BATBlock(bigBlockSize); // Fill it byte[] buffer = new byte[LittleEndian.INT_SIZE]; for(int i=0; i<block._values.length; i++) { data.get(buffer); block._values[i] = LittleEndian.getInt(buffer); } block.recomputeFree(); // All done return block; } /** * Creates a single BATBlock, with all the values set to empty. */ public static BATBlock createEmptyBATBlock(final POIFSBigBlockSize bigBlockSize, boolean isXBAT) { BATBlock block = new BATBlock(bigBlockSize); if(isXBAT) { block.setXBATChain(bigBlockSize, POIFSConstants.END_OF_CHAIN); } return block; } /** * Create an array of BATBlocks from an array of int block * allocation table entries * * @param entries the array of int entries * * @return the newly created array of BATBlocks */ public static BATBlock [] createBATBlocks(final POIFSBigBlockSize bigBlockSize, final int [] entries) { int block_count = calculateStorageRequirements(bigBlockSize, entries.length); BATBlock[] blocks = new BATBlock[ block_count ]; int index = 0; int remaining = entries.length; int _entries_per_block = bigBlockSize.getBATEntriesPerBlock(); for (int j = 0; j < entries.length; j += _entries_per_block) { blocks[ index++ ] = new BATBlock(bigBlockSize, entries, j, (remaining > _entries_per_block) ? j + _entries_per_block : entries.length); remaining -= _entries_per_block; } return blocks; } /** * Create an array of XBATBlocks from an array of int block * allocation table entries * * @param entries the array of int entries * @param startBlock the start block of the array of XBAT blocks * * @return the newly created array of BATBlocks */ public static BATBlock [] createXBATBlocks(final POIFSBigBlockSize bigBlockSize, final int [] entries, final int startBlock) { int block_count = calculateXBATStorageRequirements(bigBlockSize, entries.length); BATBlock[] blocks = new BATBlock[ block_count ]; int index = 0; int remaining = entries.length; int _entries_per_xbat_block = bigBlockSize.getXBATEntriesPerBlock(); if (block_count != 0) { for (int j = 0; j < entries.length; j += _entries_per_xbat_block) { blocks[ index++ ] = new BATBlock(bigBlockSize, entries, j, (remaining > _entries_per_xbat_block) ? j + _entries_per_xbat_block : entries.length); remaining -= _entries_per_xbat_block; } for (index = 0; index < blocks.length - 1; index++) { blocks[ index ].setXBATChain(bigBlockSize, startBlock + index + 1); } blocks[ index ].setXBATChain(bigBlockSize, POIFSConstants.END_OF_CHAIN); } return blocks; } /** * Calculate how many BATBlocks are needed to hold a specified * number of BAT entries. * * @param entryCount the number of entries * * @return the number of BATBlocks needed */ public static int calculateStorageRequirements(final POIFSBigBlockSize bigBlockSize, final int entryCount) { int _entries_per_block = bigBlockSize.getBATEntriesPerBlock(); return (entryCount + _entries_per_block - 1) / _entries_per_block; } /** * Calculate how many XBATBlocks are needed to hold a specified * number of BAT entries. * * @param entryCount the number of entries * * @return the number of XBATBlocks needed */ public static int calculateXBATStorageRequirements(final POIFSBigBlockSize bigBlockSize, final int entryCount) { int _entries_per_xbat_block = bigBlockSize.getXBATEntriesPerBlock(); return (entryCount + _entries_per_xbat_block - 1) / _entries_per_xbat_block; } /** * Calculates the maximum size of a file which is addressable given the * number of FAT (BAT) sectors specified. (We don't care if those BAT * blocks come from the 109 in the header, or from header + XBATS, it * won't affect the calculation) * * The actual file size will be between [size of fatCount-1 blocks] and * [size of fatCount blocks]. * For 512 byte block sizes, this means we may over-estimate by up to 65kb. * For 4096 byte block sizes, this means we may over-estimate by up to 4mb */ public static int calculateMaximumSize(final POIFSBigBlockSize bigBlockSize, final int numBATs) { int size = 1; // Header isn't FAT addressed // The header has up to 109 BATs, and extra ones are referenced // from XBATs // However, all BATs can contain 128/1024 blocks size += (numBATs * bigBlockSize.getBATEntriesPerBlock()); // So far we've been in sector counts, turn into bytes return size * bigBlockSize.getBigBlockSize(); } public static int calculateMaximumSize(final HeaderBlock header) { return calculateMaximumSize(header.getBigBlockSize(), header.getBATCount()); } /** * Returns the BATBlock that handles the specified offset, * and the relative index within it. * The List of BATBlocks must be in sequential order */ public static BATBlockAndIndex getBATBlockAndIndex(final int offset, final HeaderBlock header, final List<BATBlock> bats) { POIFSBigBlockSize bigBlockSize = header.getBigBlockSize(); int whichBAT = (int)Math.floor(offset / bigBlockSize.getBATEntriesPerBlock()); int index = offset % bigBlockSize.getBATEntriesPerBlock(); return new BATBlockAndIndex( index, bats.get(whichBAT) ); } /** * Returns the BATBlock that handles the specified offset, * and the relative index within it, for the mini stream. * The List of BATBlocks must be in sequential order */ public static BATBlockAndIndex getSBATBlockAndIndex(final int offset, final HeaderBlock header, final List<BATBlock> sbats) { POIFSBigBlockSize bigBlockSize = header.getBigBlockSize(); // SBATs are so much easier, as they're chained streams int whichSBAT = (int)Math.floor(offset / bigBlockSize.getBATEntriesPerBlock()); int index = offset % bigBlockSize.getBATEntriesPerBlock(); return new BATBlockAndIndex( index, sbats.get(whichSBAT) ); } private void setXBATChain(final POIFSBigBlockSize bigBlockSize, int chainIndex) { int _entries_per_xbat_block = bigBlockSize.getXBATEntriesPerBlock(); _values[ _entries_per_xbat_block ] = chainIndex; } /** * Does this BATBlock have any free sectors in it, or * is it full? */ public boolean hasFreeSectors() { return _has_free_sectors; } public int getValueAt(int relativeOffset) { if(relativeOffset >= _values.length) { throw new ArrayIndexOutOfBoundsException( "Unable to fetch offset " + relativeOffset + " as the " + "BAT only contains " + _values.length + " entries" ); } return _values[relativeOffset]; } public void setValueAt(int relativeOffset, int value) { int oldValue = _values[relativeOffset]; _values[relativeOffset] = value; // Do we need to re-compute the free? if(value == POIFSConstants.UNUSED_BLOCK) { _has_free_sectors = true; return; } if(oldValue == POIFSConstants.UNUSED_BLOCK) { recomputeFree(); } } /** * Record where in the file we live */ public void setOurBlockIndex(int index) { this.ourBlockIndex = index; } /** * Retrieve where in the file we live */ public int getOurBlockIndex() { return ourBlockIndex; } /* ********** START extension of BigBlock ********** */ /** * Write the block's data to an OutputStream * * @param stream the OutputStream to which the stored data should * be written * * @exception IOException on problems writing to the specified * stream */ void writeData(final OutputStream stream) throws IOException { // Save it out stream.write( serialize() ); } void writeData(final ByteBuffer block) throws IOException { // Save it out block.put( serialize() ); } private byte[] serialize() { // Create the empty array byte[] data = new byte[ bigBlockSize.getBigBlockSize() ]; // Fill in the values int offset = 0; for(int i=0; i<_values.length; i++) { LittleEndian.putInt(data, offset, _values[i]); offset += LittleEndian.INT_SIZE; } // Done return data; } /* ********** END extension of BigBlock ********** */ public static class BATBlockAndIndex { private final int index; private final BATBlock block; private BATBlockAndIndex(int index, BATBlock block) { this.index = index; this.block = block; } public int getIndex() { return index; } public BATBlock getBlock() { return block; } } }
neolord0/hwplib
src/main/java/kr/dogfoot/hwplib/org/apache/poi/poifs/storage/BATBlock.java
214,036
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.shiro.web.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; /** * View that redirects to an absolute, context relative, or current request * relative URL, exposing all model attributes as HTTP query parameters. * <p/> * A URL for this view is supposed to be a HTTP redirect URL, i.e. * suitable for HttpServletResponse's <code>sendRedirect</code> method, which * is what actually does the redirect if the HTTP 1.0 flag is on, or via sending * back an HTTP 303 code - if the HTTP 1.0 compatibility flag is off. * <p/> * Note that while the default value for the "contextRelative" flag is off, * you will probably want to almost always set it to true. With the flag off, * URLs starting with "/" are considered relative to the web server root, while * with the flag on, they are considered relative to the web application root. * Since most web apps will never know or care what their context path actually * is, they are much better off setting this flag to true, and submitting paths * which are to be considered relative to the web application root. * <p/> * Note that in a Servlet 2.2 environment, i.e. a servlet container which * is only compliant to the limits of this spec, this class will probably fail * when feeding in URLs which are not fully absolute, or relative to the current * request (no leading "/"), as these are the only two types of URL that * <code>sendRedirect</code> supports in a Servlet 2.2 environment. * <p/> * <em>This class was borrowed from a nearly identical version found in * the <a href="http://www.springframework.org/">Spring Framework</a>, with minor modifications to * avoid a dependency on Spring itself for a very small amount of code - we couldn't have done it better, and * don't want to repeat all of their great effort ;). * The original author names and copyright (Apache 2.0) has been left in place. A special * thanks to Rod Johnson, Juergen Hoeller, and Colin Sampaleanu for making this available.</em> * * @see #setContextRelative * @see #setHttp10Compatible * @see javax.servlet.http.HttpServletResponse#sendRedirect * @since 0.2 */ public class RedirectView { //TODO - complete JavaDoc /** * The default encoding scheme: UTF-8 */ public static final String DEFAULT_ENCODING_SCHEME = "UTF-8"; private String url; private boolean contextRelative; private boolean http10Compatible = true; private String encodingScheme = DEFAULT_ENCODING_SCHEME; /** * Constructor for use as a bean. */ @SuppressWarnings({"UnusedDeclaration"}) public RedirectView() { } /** * Create a new RedirectView with the given URL. * <p>The given URL will be considered as relative to the web server, * not as relative to the current ServletContext. * * @param url the URL to redirect to * @see #RedirectView(String, boolean) */ public RedirectView(String url) { setUrl(url); } /** * Create a new RedirectView with the given URL. * * @param url the URL to redirect to * @param contextRelative whether to interpret the given URL as * relative to the current ServletContext */ public RedirectView(String url, boolean contextRelative) { this(url); this.contextRelative = contextRelative; } /** * Create a new RedirectView with the given URL. * * @param url the URL to redirect to * @param contextRelative whether to interpret the given URL as * relative to the current ServletContext * @param http10Compatible whether to stay compatible with HTTP 1.0 clients */ public RedirectView(String url, boolean contextRelative, boolean http10Compatible) { this(url); this.contextRelative = contextRelative; this.http10Compatible = http10Compatible; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } /** * Set whether to interpret a given URL that starts with a slash ("/") * as relative to the current ServletContext, i.e. as relative to the * web application root. * <p/> * Default is "false": A URL that starts with a slash will be interpreted * as absolute, i.e. taken as-is. If true, the context path will be * prepended to the URL in such a case. * * @param contextRelative whether to interpret a given URL that starts with a slash ("/") * as relative to the current ServletContext, i.e. as relative to the * web application root. * @see javax.servlet.http.HttpServletRequest#getContextPath */ public void setContextRelative(boolean contextRelative) { this.contextRelative = contextRelative; } /** * Set whether to stay compatible with HTTP 1.0 clients. * <p>In the default implementation, this will enforce HTTP status code 302 * in any case, i.e. delegate to <code>HttpServletResponse.sendRedirect</code>. * Turning this off will send HTTP status code 303, which is the correct * code for HTTP 1.1 clients, but not understood by HTTP 1.0 clients. * <p>Many HTTP 1.1 clients treat 302 just like 303, not making any * difference. However, some clients depend on 303 when redirecting * after a POST request; turn this flag off in such a scenario. * * @param http10Compatible whether to stay compatible with HTTP 1.0 clients. * @see javax.servlet.http.HttpServletResponse#sendRedirect */ public void setHttp10Compatible(boolean http10Compatible) { this.http10Compatible = http10Compatible; } /** * Set the encoding scheme for this view. Default is UTF-8. * * @param encodingScheme the encoding scheme for this view. Default is UTF-8. */ @SuppressWarnings({"UnusedDeclaration"}) public void setEncodingScheme(String encodingScheme) { this.encodingScheme = encodingScheme; } /** * Convert model to request parameters and redirect to the given URL. * * @param model the model to convert * @param request the incoming HttpServletRequest * @param response the outgoing HttpServletResponse * @throws java.io.IOException if there is a problem issuing the redirect * @see #appendQueryProperties * @see #sendRedirect */ public final void renderMergedOutputModel( Map model, HttpServletRequest request, HttpServletResponse response) throws IOException { // Prepare name URL. StringBuilder targetUrl = new StringBuilder(); if (this.contextRelative && getUrl().startsWith("/")) { // Do not apply context path to relative URLs. targetUrl.append(request.getContextPath()); } targetUrl.append(getUrl()); //change the following method to accept a StringBuilder instead of a StringBuilder for Shiro 2.x: appendQueryProperties(targetUrl, model, this.encodingScheme); sendRedirect(request, response, targetUrl.toString(), this.http10Compatible); } /** * Append query properties to the redirect URL. * Stringifies, URL-encodes and formats model attributes as query properties. * * @param targetUrl the StringBuffer to append the properties to * @param model Map that contains model attributes * @param encodingScheme the encoding scheme to use * @throws java.io.UnsupportedEncodingException if string encoding failed * @see #urlEncode * @see #queryProperties * @see #urlEncode(String, String) */ protected void appendQueryProperties(StringBuilder targetUrl, Map model, String encodingScheme) throws UnsupportedEncodingException { // Extract anchor fragment, if any. // The following code does not use JDK 1.4's StringBuffer.indexOf(String) // method to retain JDK 1.3 compatibility. String fragment = null; int anchorIndex = targetUrl.toString().indexOf('#'); if (anchorIndex > -1) { fragment = targetUrl.substring(anchorIndex); targetUrl.delete(anchorIndex, targetUrl.length()); } // If there aren't already some parameters, we need a "?". boolean first = (getUrl().indexOf('?') < 0); Map queryProps = queryProperties(model); if (queryProps != null) { for (Object o : queryProps.entrySet()) { if (first) { targetUrl.append('?'); first = false; } else { targetUrl.append('&'); } Map.Entry entry = (Map.Entry) o; String encodedKey = urlEncode(entry.getKey().toString(), encodingScheme); String encodedValue = (entry.getValue() != null ? urlEncode(entry.getValue().toString(), encodingScheme) : ""); targetUrl.append(encodedKey).append('=').append(encodedValue); } } // Append anchor fragment, if any, to end of URL. if (fragment != null) { targetUrl.append(fragment); } } /** * URL-encode the given input String with the given encoding scheme, using * {@link URLEncoder#encode(String, String) URLEncoder.encode(input, enc)}. * * @param input the unencoded input String * @param encodingScheme the encoding scheme * @return the encoded output String * @throws UnsupportedEncodingException if thrown by the JDK URLEncoder * @see java.net.URLEncoder#encode(String, String) * @see java.net.URLEncoder#encode(String) */ protected String urlEncode(String input, String encodingScheme) throws UnsupportedEncodingException { return URLEncoder.encode(input, encodingScheme); } /** * Determine name-value pairs for query strings, which will be stringified, * URL-encoded and formatted by appendQueryProperties. * <p/> * This implementation returns all model elements as-is. * * @param model the model elements for which to determine name-value pairs. * @return the name-value pairs for query strings. * @see #appendQueryProperties */ protected Map queryProperties(Map model) { return model; } /** * Send a redirect back to the HTTP client * * @param request current HTTP request (allows for reacting to request method) * @param response current HTTP response (for sending response headers) * @param targetUrl the name URL to redirect to * @param http10Compatible whether to stay compatible with HTTP 1.0 clients * @throws IOException if thrown by response methods */ protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String targetUrl, boolean http10Compatible) throws IOException { String encodedRedirectURL = response.encodeRedirectURL(targetUrl); if (http10Compatible) { // Always send status code 302. response.sendRedirect(encodedRedirectURL); } else { // Correct HTTP status code is 303, in particular for POST requests. response.setStatus(HttpServletResponse.SC_SEE_OTHER); response.setHeader("Location", encodedRedirectURL); } } }
apache/shiro
web/src/main/java/org/apache/shiro/web/util/RedirectView.java
214,037
/* * Encog(tm) Core v3.4 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2017 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.util.data; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import org.encog.EncogError; import org.encog.ml.data.MLData; import org.encog.ml.data.MLDataSet; import org.encog.ml.data.basic.BasicMLData; import org.encog.ml.data.basic.BasicMLDataPair; import org.encog.ml.data.basic.BasicMLDataSet; /** * This reads the MNIST dataset of handwritten digits into an Encog data set. * The MNIST dataset is found at http://yann.lecun.com/exdb/mnist/. * * Adapted from a class by Gabe Johnson &lt;[email protected]&gt;. * https://code.google.com * /p/pen-ui/source/browse/trunk/skrui/src/org/six11/skrui * /charrec/MNISTReader.java?r=185 */ public class MNISTReader { private final int numLabels; private final int numImages; private final int numRows; private final int numCols; private final MLDataSet data; public MNISTReader(String labelFilename, String imageFilename) { try { DataInputStream labels = new DataInputStream(new FileInputStream( labelFilename)); DataInputStream images = new DataInputStream(new FileInputStream( imageFilename)); int magicNumber = labels.readInt(); if (magicNumber != 2049) { throw new EncogError("Label file has wrong magic number: " + magicNumber + " (should be 2049)"); } magicNumber = images.readInt(); if (magicNumber != 2051) { throw new EncogError("Image file has wrong magic number: " + magicNumber + " (should be 2051)"); } this.numLabels = labels.readInt(); this.numImages = images.readInt(); this.numRows = images.readInt(); this.numCols = images.readInt(); if (numLabels != numImages) { StringBuilder str = new StringBuilder(); str.append("Image file and label file do not contain the same number of entries.\n"); str.append(" Label file contains: " + numLabels + "\n"); str.append(" Image file contains: " + numImages + "\n"); throw new EncogError(str.toString()); } byte[] labelsData = new byte[numLabels]; labels.read(labelsData); int imageVectorSize = numCols * numRows; byte[] imagesData = new byte[numLabels * imageVectorSize]; images.read(imagesData); this.data = new BasicMLDataSet(); int imageIndex = 0; for(int i=0;i<this.numLabels;i++) { int label = labelsData[i]; MLData inputData = new BasicMLData(imageVectorSize); for(int j=0;j<imageVectorSize;j++) { inputData.setData(j, ((double)(imagesData[imageIndex++]&0xff))/255.0); } MLData idealData = new BasicMLData(10); idealData.setData(label, 1.0); this.data.add(new BasicMLDataPair(inputData,idealData)); } images.close(); labels.close(); } catch (IOException ex) { throw new EncogError(ex); } } /** * @return the numLabels */ public int getNumLabels() { return numLabels; } /** * @return the numImages */ public int getNumImages() { return numImages; } /** * @return the numRows */ public int getNumRows() { return numRows; } /** * @return the numCols */ public int getNumCols() { return numCols; } /** * @return the data */ public MLDataSet getData() { return data; } }
jeffheaton/encog-java-core
src/main/java/org/encog/util/data/MNISTReader.java
214,038
/* * Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. All rights reserved. * * 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.didi.virtualapk.internal; import android.annotation.TargetApi; import android.app.Application; import android.app.Instrumentation; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.ChangedPackages; import android.content.pm.FeatureInfo; import android.content.pm.InstrumentationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageInstaller; import android.content.pm.PackageItemInfo; import android.content.pm.PackageManager; import android.content.pm.PackageParser; import android.content.pm.PermissionGroupInfo; import android.content.pm.PermissionInfo; import android.content.pm.ProviderInfo; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.content.pm.SharedLibraryInfo; import android.content.pm.VersionedPackage; import android.content.res.AssetManager; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Process; import android.os.UserHandle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.didi.virtualapk.PluginManager; import com.didi.virtualapk.internal.utils.DexUtil; import com.didi.virtualapk.internal.utils.PackageParserCompat; import com.didi.virtualapk.internal.utils.PluginUtil; import com.didi.virtualapk.utils.Reflector; import com.didi.virtualapk.utils.RunUtil; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import dalvik.system.DexClassLoader; /** * Created by renyugang on 16/8/9. */ public class LoadedPlugin { public static final String TAG = Constants.TAG_PREFIX + "LoadedPlugin"; protected File getDir(Context context, String name) { return context.getDir(name, Context.MODE_PRIVATE); } protected ClassLoader createClassLoader(Context context, File apk, File libsDir, ClassLoader parent) throws Exception { File dexOutputDir = getDir(context, Constants.OPTIMIZE_DIR); String dexOutputPath = dexOutputDir.getAbsolutePath(); DexClassLoader loader = new DexClassLoader(apk.getAbsolutePath(), dexOutputPath, libsDir.getAbsolutePath(), parent); if (Constants.COMBINE_CLASSLOADER) { DexUtil.insertDex(loader, parent, libsDir); } return loader; } protected AssetManager createAssetManager(Context context, File apk) throws Exception { AssetManager am = AssetManager.class.newInstance(); Reflector.with(am).method("addAssetPath", String.class).call(apk.getAbsolutePath()); return am; } protected Resources createResources(Context context, String packageName, File apk) throws Exception { if (Constants.COMBINE_RESOURCES) { return ResourcesManager.createResources(context, packageName, apk); } else { Resources hostResources = context.getResources(); AssetManager assetManager = createAssetManager(context, apk); return new Resources(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration()); } } protected PluginPackageManager createPluginPackageManager() { return new PluginPackageManager(); } public PluginContext createPluginContext(Context context) { if (context == null) { return new PluginContext(this); } return new PluginContext(this, context); } protected ResolveInfo chooseBestActivity(Intent intent, String s, int flags, List<ResolveInfo> query) { return query.get(0); } protected final String mLocation; protected PluginManager mPluginManager; protected Context mHostContext; protected Context mPluginContext; protected final File mNativeLibDir; protected final PackageParser.Package mPackage; protected final PackageInfo mPackageInfo; protected Resources mResources; protected ClassLoader mClassLoader; protected PluginPackageManager mPackageManager; protected Map<ComponentName, ActivityInfo> mActivityInfos; protected Map<ComponentName, ServiceInfo> mServiceInfos; protected Map<ComponentName, ActivityInfo> mReceiverInfos; protected Map<ComponentName, ProviderInfo> mProviderInfos; protected Map<String, ProviderInfo> mProviders; // key is authorities of provider protected Map<ComponentName, InstrumentationInfo> mInstrumentationInfos; protected Application mApplication; public LoadedPlugin(PluginManager pluginManager, Context context, File apk) throws Exception { this.mPluginManager = pluginManager; this.mHostContext = context; this.mLocation = apk.getAbsolutePath(); this.mPackage = PackageParserCompat.parsePackage(context, apk, PackageParser.PARSE_MUST_BE_APK); this.mPackage.applicationInfo.metaData = this.mPackage.mAppMetaData; this.mPackageInfo = new PackageInfo(); this.mPackageInfo.applicationInfo = this.mPackage.applicationInfo; this.mPackageInfo.applicationInfo.sourceDir = apk.getAbsolutePath(); if (Build.VERSION.SDK_INT >= 28 || (Build.VERSION.SDK_INT == 27 && Build.VERSION.PREVIEW_SDK_INT != 0)) { // Android P Preview try { this.mPackageInfo.signatures = this.mPackage.mSigningDetails.signatures; } catch (Throwable e) { PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES); this.mPackageInfo.signatures = info.signatures; } } else { this.mPackageInfo.signatures = this.mPackage.mSignatures; } this.mPackageInfo.packageName = this.mPackage.packageName; if (pluginManager.getLoadedPlugin(mPackageInfo.packageName) != null) { throw new RuntimeException("plugin has already been loaded : " + mPackageInfo.packageName); } this.mPackageInfo.versionCode = this.mPackage.mVersionCode; this.mPackageInfo.versionName = this.mPackage.mVersionName; this.mPackageInfo.permissions = new PermissionInfo[0]; this.mPackageManager = createPluginPackageManager(); this.mPluginContext = createPluginContext(null); this.mNativeLibDir = getDir(context, Constants.NATIVE_DIR); this.mPackage.applicationInfo.nativeLibraryDir = this.mNativeLibDir.getAbsolutePath(); this.mResources = createResources(context, getPackageName(), apk); this.mClassLoader = createClassLoader(context, apk, this.mNativeLibDir, context.getClassLoader()); tryToCopyNativeLib(apk); // Cache instrumentations Map<ComponentName, InstrumentationInfo> instrumentations = new HashMap<ComponentName, InstrumentationInfo>(); for (PackageParser.Instrumentation instrumentation : this.mPackage.instrumentation) { instrumentations.put(instrumentation.getComponentName(), instrumentation.info); } this.mInstrumentationInfos = Collections.unmodifiableMap(instrumentations); this.mPackageInfo.instrumentation = instrumentations.values().toArray(new InstrumentationInfo[instrumentations.size()]); // Cache activities Map<ComponentName, ActivityInfo> activityInfos = new HashMap<ComponentName, ActivityInfo>(); for (PackageParser.Activity activity : this.mPackage.activities) { activity.info.metaData = activity.metaData; activityInfos.put(activity.getComponentName(), activity.info); } this.mActivityInfos = Collections.unmodifiableMap(activityInfos); this.mPackageInfo.activities = activityInfos.values().toArray(new ActivityInfo[activityInfos.size()]); // Cache services Map<ComponentName, ServiceInfo> serviceInfos = new HashMap<ComponentName, ServiceInfo>(); for (PackageParser.Service service : this.mPackage.services) { serviceInfos.put(service.getComponentName(), service.info); } this.mServiceInfos = Collections.unmodifiableMap(serviceInfos); this.mPackageInfo.services = serviceInfos.values().toArray(new ServiceInfo[serviceInfos.size()]); // Cache providers Map<String, ProviderInfo> providers = new HashMap<String, ProviderInfo>(); Map<ComponentName, ProviderInfo> providerInfos = new HashMap<ComponentName, ProviderInfo>(); for (PackageParser.Provider provider : this.mPackage.providers) { providers.put(provider.info.authority, provider.info); providerInfos.put(provider.getComponentName(), provider.info); } this.mProviders = Collections.unmodifiableMap(providers); this.mProviderInfos = Collections.unmodifiableMap(providerInfos); this.mPackageInfo.providers = providerInfos.values().toArray(new ProviderInfo[providerInfos.size()]); // Register broadcast receivers dynamically Map<ComponentName, ActivityInfo> receivers = new HashMap<ComponentName, ActivityInfo>(); for (PackageParser.Activity receiver : this.mPackage.receivers) { receivers.put(receiver.getComponentName(), receiver.info); BroadcastReceiver br = BroadcastReceiver.class.cast(getClassLoader().loadClass(receiver.getComponentName().getClassName()).newInstance()); for (PackageParser.ActivityIntentInfo aii : receiver.intents) { this.mHostContext.registerReceiver(br, aii); } } this.mReceiverInfos = Collections.unmodifiableMap(receivers); this.mPackageInfo.receivers = receivers.values().toArray(new ActivityInfo[receivers.size()]); // try to invoke plugin's application invokeApplication(); } protected void tryToCopyNativeLib(File apk) throws Exception { PluginUtil.copyNativeLib(apk, mHostContext, mPackageInfo, mNativeLibDir); } public String getLocation() { return this.mLocation; } public String getPackageName() { return this.mPackage.packageName; } public PackageManager getPackageManager() { return this.mPackageManager; } public AssetManager getAssets() { return getResources().getAssets(); } public Resources getResources() { return this.mResources; } public void updateResources(Resources newResources) { this.mResources = newResources; } public ClassLoader getClassLoader() { return this.mClassLoader; } public PluginManager getPluginManager() { return this.mPluginManager; } public Context getHostContext() { return this.mHostContext; } public Context getPluginContext() { return this.mPluginContext; } public Application getApplication() { return mApplication; } public void invokeApplication() throws Exception { final Exception[] temp = new Exception[1]; // make sure application's callback is run on ui thread. RunUtil.runOnUiThread(new Runnable() { @Override public void run() { if (mApplication != null) { return; } try { mApplication = makeApplication(false, mPluginManager.getInstrumentation()); } catch (Exception e) { temp[0] = e; } } }, true); if (temp[0] != null) { throw temp[0]; } } public String getPackageResourcePath() { int myUid = Process.myUid(); ApplicationInfo appInfo = this.mPackage.applicationInfo; return appInfo.uid == myUid ? appInfo.sourceDir : appInfo.publicSourceDir; } public String getCodePath() { return this.mPackage.applicationInfo.sourceDir; } public Intent getLaunchIntent() { ContentResolver resolver = this.mPluginContext.getContentResolver(); Intent launcher = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER); for (PackageParser.Activity activity : this.mPackage.activities) { for (PackageParser.ActivityIntentInfo intentInfo : activity.intents) { if (intentInfo.match(resolver, launcher, false, TAG) > 0) { return Intent.makeMainActivity(activity.getComponentName()); } } } return null; } public Intent getLeanbackLaunchIntent() { ContentResolver resolver = this.mPluginContext.getContentResolver(); Intent launcher = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER); for (PackageParser.Activity activity : this.mPackage.activities) { for (PackageParser.ActivityIntentInfo intentInfo : activity.intents) { if (intentInfo.match(resolver, launcher, false, TAG) > 0) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setComponent(activity.getComponentName()); intent.addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER); return intent; } } } return null; } public ApplicationInfo getApplicationInfo() { return this.mPackage.applicationInfo; } public PackageInfo getPackageInfo() { return this.mPackageInfo; } public ActivityInfo getActivityInfo(ComponentName componentName) { return this.mActivityInfos.get(componentName); } public ServiceInfo getServiceInfo(ComponentName componentName) { return this.mServiceInfos.get(componentName); } public ActivityInfo getReceiverInfo(ComponentName componentName) { return this.mReceiverInfos.get(componentName); } public ProviderInfo getProviderInfo(ComponentName componentName) { return this.mProviderInfos.get(componentName); } public Resources.Theme getTheme() { Resources.Theme theme = this.mResources.newTheme(); theme.applyStyle(PluginUtil.selectDefaultTheme(this.mPackage.applicationInfo.theme, Build.VERSION.SDK_INT), false); return theme; } public void setTheme(int resid) { Reflector.QuietReflector.with(this.mResources).field("mThemeResId").set(resid); } protected Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) throws Exception { if (null != this.mApplication) { return this.mApplication; } String appClass = this.mPackage.applicationInfo.className; if (forceDefaultAppClass || null == appClass) { appClass = "android.app.Application"; } this.mApplication = instrumentation.newApplication(this.mClassLoader, appClass, this.getPluginContext()); // inject activityLifecycleCallbacks of the host application mApplication.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacksProxy()); instrumentation.callApplicationOnCreate(this.mApplication); return this.mApplication; } public ResolveInfo resolveActivity(Intent intent, int flags) { List<ResolveInfo> query = this.queryIntentActivities(intent, flags); if (null == query || query.isEmpty()) { return null; } ContentResolver resolver = this.mPluginContext.getContentResolver(); return chooseBestActivity(intent, intent.resolveTypeIfNeeded(resolver), flags, query); } public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) { ComponentName component = intent.getComponent(); List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>(); ContentResolver resolver = this.mPluginContext.getContentResolver(); for (PackageParser.Activity activity : this.mPackage.activities) { if (match(activity, component)) { ResolveInfo resolveInfo = new ResolveInfo(); resolveInfo.activityInfo = activity.info; resolveInfos.add(resolveInfo); } else if (component == null) { // only match implicit intent for (PackageParser.ActivityIntentInfo intentInfo : activity.intents) { if (intentInfo.match(resolver, intent, true, TAG) >= 0) { ResolveInfo resolveInfo = new ResolveInfo(); resolveInfo.activityInfo = activity.info; resolveInfos.add(resolveInfo); break; } } } } return resolveInfos; } public ResolveInfo resolveService(Intent intent, int flags) { List<ResolveInfo> query = this.queryIntentServices(intent, flags); if (null == query || query.isEmpty()) { return null; } ContentResolver resolver = this.mPluginContext.getContentResolver(); return chooseBestActivity(intent, intent.resolveTypeIfNeeded(resolver), flags, query); } public List<ResolveInfo> queryIntentServices(Intent intent, int flags) { ComponentName component = intent.getComponent(); List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>(); ContentResolver resolver = this.mPluginContext.getContentResolver(); for (PackageParser.Service service : this.mPackage.services) { if (match(service, component)) { ResolveInfo resolveInfo = new ResolveInfo(); resolveInfo.serviceInfo = service.info; resolveInfos.add(resolveInfo); } else if (component == null) { // only match implicit intent for (PackageParser.ServiceIntentInfo intentInfo : service.intents) { if (intentInfo.match(resolver, intent, true, TAG) >= 0) { ResolveInfo resolveInfo = new ResolveInfo(); resolveInfo.serviceInfo = service.info; resolveInfos.add(resolveInfo); break; } } } } return resolveInfos; } public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) { ComponentName component = intent.getComponent(); List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>(); ContentResolver resolver = this.mPluginContext.getContentResolver(); for (PackageParser.Activity receiver : this.mPackage.receivers) { if (receiver.getComponentName().equals(component)) { ResolveInfo resolveInfo = new ResolveInfo(); resolveInfo.activityInfo = receiver.info; resolveInfos.add(resolveInfo); } else if (component == null) { // only match implicit intent for (PackageParser.ActivityIntentInfo intentInfo : receiver.intents) { if (intentInfo.match(resolver, intent, true, TAG) >= 0) { ResolveInfo resolveInfo = new ResolveInfo(); resolveInfo.activityInfo = receiver.info; resolveInfos.add(resolveInfo); break; } } } } return resolveInfos; } public ProviderInfo resolveContentProvider(String name, int flags) { return this.mProviders.get(name); } protected boolean match(PackageParser.Component component, ComponentName target) { ComponentName source = component.getComponentName(); if (source == target) return true; if (source != null && target != null && source.getClassName().equals(target.getClassName()) && (source.getPackageName().equals(target.getPackageName()) || mHostContext.getPackageName().equals(target.getPackageName()))) { return true; } return false; } /** * @author johnsonlee */ protected class PluginPackageManager extends PackageManager { protected PackageManager mHostPackageManager = mHostContext.getPackageManager(); @Override public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return plugin.mPackageInfo; } return this.mHostPackageManager.getPackageInfo(packageName, flags); } @TargetApi(Build.VERSION_CODES.O) @Override public PackageInfo getPackageInfo(VersionedPackage versionedPackage, int i) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(versionedPackage.getPackageName()); if (null != plugin) { return plugin.mPackageInfo; } return this.mHostPackageManager.getPackageInfo(versionedPackage, i); } @Override public String[] currentToCanonicalPackageNames(String[] names) { return this.mHostPackageManager.currentToCanonicalPackageNames(names); } @Override public String[] canonicalToCurrentPackageNames(String[] names) { return this.mHostPackageManager.canonicalToCurrentPackageNames(names); } @Override public Intent getLaunchIntentForPackage(@NonNull String packageName) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return plugin.getLaunchIntent(); } return this.mHostPackageManager.getLaunchIntentForPackage(packageName); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public Intent getLeanbackLaunchIntentForPackage(@NonNull String packageName) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return plugin.getLeanbackLaunchIntent(); } return this.mHostPackageManager.getLeanbackLaunchIntentForPackage(packageName); } @Override public int[] getPackageGids(@NonNull String packageName) throws NameNotFoundException { return this.mHostPackageManager.getPackageGids(packageName); } @TargetApi(Build.VERSION_CODES.N) @Override public int[] getPackageGids(String packageName, int flags) throws NameNotFoundException { return this.mHostPackageManager.getPackageGids(packageName, flags); } @TargetApi(Build.VERSION_CODES.N) @Override public int getPackageUid(String packageName, int flags) throws NameNotFoundException { return this.mHostPackageManager.getPackageUid(packageName, flags); } @Override public PermissionInfo getPermissionInfo(String name, int flags) throws NameNotFoundException { return this.mHostPackageManager.getPermissionInfo(name, flags); } @Override public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) throws NameNotFoundException { return this.mHostPackageManager.queryPermissionsByGroup(group, flags); } @Override public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) throws NameNotFoundException { return this.mHostPackageManager.getPermissionGroupInfo(name, flags); } @Override public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { return this.mHostPackageManager.getAllPermissionGroups(flags); } @Override public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return plugin.getApplicationInfo(); } return this.mHostPackageManager.getApplicationInfo(packageName, flags); } @Override public ActivityInfo getActivityInfo(ComponentName component, int flags) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { return plugin.mActivityInfos.get(component); } return this.mHostPackageManager.getActivityInfo(component, flags); } @Override public ActivityInfo getReceiverInfo(ComponentName component, int flags) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { return plugin.mReceiverInfos.get(component); } return this.mHostPackageManager.getReceiverInfo(component, flags); } @Override public ServiceInfo getServiceInfo(ComponentName component, int flags) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { return plugin.mServiceInfos.get(component); } return this.mHostPackageManager.getServiceInfo(component, flags); } @Override public ProviderInfo getProviderInfo(ComponentName component, int flags) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { return plugin.mProviderInfos.get(component); } return this.mHostPackageManager.getProviderInfo(component, flags); } @Override public List<PackageInfo> getInstalledPackages(int flags) { return this.mHostPackageManager.getInstalledPackages(flags); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) @Override public List<PackageInfo> getPackagesHoldingPermissions(String[] permissions, int flags) { return this.mHostPackageManager.getPackagesHoldingPermissions(permissions, flags); } @Override public int checkPermission(String permName, String pkgName) { return this.mHostPackageManager.checkPermission(permName, pkgName); } @TargetApi(Build.VERSION_CODES.M) @Override public boolean isPermissionRevokedByPolicy(@NonNull String permName, @NonNull String pkgName) { return this.mHostPackageManager.isPermissionRevokedByPolicy(permName, pkgName); } @Override public boolean addPermission(PermissionInfo info) { return this.mHostPackageManager.addPermission(info); } @Override public boolean addPermissionAsync(PermissionInfo info) { return this.mHostPackageManager.addPermissionAsync(info); } @Override public void removePermission(String name) { this.mHostPackageManager.removePermission(name); } @Override public int checkSignatures(String pkg1, String pkg2) { return this.mHostPackageManager.checkSignatures(pkg1, pkg2); } @Override public int checkSignatures(int uid1, int uid2) { return this.mHostPackageManager.checkSignatures(uid1, uid2); } @Override public String[] getPackagesForUid(int uid) { return this.mHostPackageManager.getPackagesForUid(uid); } @Override public String getNameForUid(int uid) { return this.mHostPackageManager.getNameForUid(uid); } @Override public List<ApplicationInfo> getInstalledApplications(int flags) { return this.mHostPackageManager.getInstalledApplications(flags); } @TargetApi(Build.VERSION_CODES.O) @Override public boolean isInstantApp() { return this.mHostPackageManager.isInstantApp(); } @TargetApi(Build.VERSION_CODES.O) @Override public boolean isInstantApp(String packageName) { return this.mHostPackageManager.isInstantApp(packageName); } @TargetApi(Build.VERSION_CODES.O) @Override public int getInstantAppCookieMaxBytes() { return this.mHostPackageManager.getInstantAppCookieMaxBytes(); } @TargetApi(Build.VERSION_CODES.O) @NonNull @Override public byte[] getInstantAppCookie() { return this.mHostPackageManager.getInstantAppCookie(); } @TargetApi(Build.VERSION_CODES.O) @Override public void clearInstantAppCookie() { this.mHostPackageManager.clearInstantAppCookie(); } @TargetApi(Build.VERSION_CODES.O) @Override public void updateInstantAppCookie(@Nullable byte[] cookie) { this.mHostPackageManager.updateInstantAppCookie(cookie); } @Override public String[] getSystemSharedLibraryNames() { return this.mHostPackageManager.getSystemSharedLibraryNames(); } @TargetApi(Build.VERSION_CODES.O) @NonNull @Override public List<SharedLibraryInfo> getSharedLibraries(int flags) { return this.mHostPackageManager.getSharedLibraries(flags); } @TargetApi(Build.VERSION_CODES.O) @Nullable @Override public ChangedPackages getChangedPackages(int sequenceNumber) { return this.mHostPackageManager.getChangedPackages(sequenceNumber); } @Override public FeatureInfo[] getSystemAvailableFeatures() { return this.mHostPackageManager.getSystemAvailableFeatures(); } @Override public boolean hasSystemFeature(String name) { return this.mHostPackageManager.hasSystemFeature(name); } @TargetApi(Build.VERSION_CODES.N) @Override public boolean hasSystemFeature(String name, int version) { return this.mHostPackageManager.hasSystemFeature(name, version); } @Override public ResolveInfo resolveActivity(Intent intent, int flags) { ResolveInfo resolveInfo = mPluginManager.resolveActivity(intent, flags); if (null != resolveInfo) { return resolveInfo; } return this.mHostPackageManager.resolveActivity(intent, flags); } @Override public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) { ComponentName component = intent.getComponent(); if (null == component) { if (intent.getSelector() != null) { intent = intent.getSelector(); component = intent.getComponent(); } } if (null != component) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { ActivityInfo activityInfo = plugin.getActivityInfo(component); if (activityInfo != null) { ResolveInfo resolveInfo = new ResolveInfo(); resolveInfo.activityInfo = activityInfo; return Arrays.asList(resolveInfo); } } } List<ResolveInfo> all = new ArrayList<ResolveInfo>(); List<ResolveInfo> pluginResolveInfos = mPluginManager.queryIntentActivities(intent, flags); if (null != pluginResolveInfos && pluginResolveInfos.size() > 0) { all.addAll(pluginResolveInfos); } List<ResolveInfo> hostResolveInfos = this.mHostPackageManager.queryIntentActivities(intent, flags); if (null != hostResolveInfos && hostResolveInfos.size() > 0) { all.addAll(hostResolveInfos); } return all; } @Override public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, Intent[] specifics, Intent intent, int flags) { return this.mHostPackageManager.queryIntentActivityOptions(caller, specifics, intent, flags); } @Override public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) { ComponentName component = intent.getComponent(); if (null == component) { if (intent.getSelector() != null) { intent = intent.getSelector(); component = intent.getComponent(); } } if (null != component) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { ActivityInfo activityInfo = plugin.getReceiverInfo(component); if (activityInfo != null) { ResolveInfo resolveInfo = new ResolveInfo(); resolveInfo.activityInfo = activityInfo; return Arrays.asList(resolveInfo); } } } List<ResolveInfo> all = new ArrayList<>(); List<ResolveInfo> pluginResolveInfos = mPluginManager.queryBroadcastReceivers(intent, flags); if (null != pluginResolveInfos && pluginResolveInfos.size() > 0) { all.addAll(pluginResolveInfos); } List<ResolveInfo> hostResolveInfos = this.mHostPackageManager.queryBroadcastReceivers(intent, flags); if (null != hostResolveInfos && hostResolveInfos.size() > 0) { all.addAll(hostResolveInfos); } return all; } @Override public ResolveInfo resolveService(Intent intent, int flags) { ResolveInfo resolveInfo = mPluginManager.resolveService(intent, flags); if (null != resolveInfo) { return resolveInfo; } return this.mHostPackageManager.resolveService(intent, flags); } @Override public List<ResolveInfo> queryIntentServices(Intent intent, int flags) { ComponentName component = intent.getComponent(); if (null == component) { if (intent.getSelector() != null) { intent = intent.getSelector(); component = intent.getComponent(); } } if (null != component) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { ServiceInfo serviceInfo = plugin.getServiceInfo(component); if (serviceInfo != null) { ResolveInfo resolveInfo = new ResolveInfo(); resolveInfo.serviceInfo = serviceInfo; return Arrays.asList(resolveInfo); } } } List<ResolveInfo> all = new ArrayList<ResolveInfo>(); List<ResolveInfo> pluginResolveInfos = mPluginManager.queryIntentServices(intent, flags); if (null != pluginResolveInfos && pluginResolveInfos.size() > 0) { all.addAll(pluginResolveInfos); } List<ResolveInfo> hostResolveInfos = this.mHostPackageManager.queryIntentServices(intent, flags); if (null != hostResolveInfos && hostResolveInfos.size() > 0) { all.addAll(hostResolveInfos); } return all; } @Override @TargetApi(Build.VERSION_CODES.KITKAT) public List<ResolveInfo> queryIntentContentProviders(Intent intent, int flags) { return this.mHostPackageManager.queryIntentContentProviders(intent, flags); } @Override public ProviderInfo resolveContentProvider(String name, int flags) { ProviderInfo providerInfo = mPluginManager.resolveContentProvider(name, flags); if (null != providerInfo) { return providerInfo; } return this.mHostPackageManager.resolveContentProvider(name, flags); } @Override public List<ProviderInfo> queryContentProviders(String processName, int uid, int flags) { return this.mHostPackageManager.queryContentProviders(processName, uid, flags); } @Override public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { return plugin.mInstrumentationInfos.get(component); } return this.mHostPackageManager.getInstrumentationInfo(component, flags); } @Override public List<InstrumentationInfo> queryInstrumentation(String targetPackage, int flags) { return this.mHostPackageManager.queryInstrumentation(targetPackage, flags); } @Override public Drawable getDrawable(String packageName, int resid, ApplicationInfo appInfo) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return plugin.mResources.getDrawable(resid); } return this.mHostPackageManager.getDrawable(packageName, resid, appInfo); } @Override public Drawable getActivityIcon(ComponentName component) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { return plugin.mResources.getDrawable(plugin.mActivityInfos.get(component).icon); } return this.mHostPackageManager.getActivityIcon(component); } @Override public Drawable getActivityIcon(Intent intent) throws NameNotFoundException { ResolveInfo ri = mPluginManager.resolveActivity(intent); if (null != ri) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(ri.resolvePackageName); return plugin.mResources.getDrawable(ri.activityInfo.icon); } return this.mHostPackageManager.getActivityIcon(intent); } @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) @Override public Drawable getActivityBanner(ComponentName component) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { return plugin.mResources.getDrawable(plugin.mActivityInfos.get(component).banner); } return this.mHostPackageManager.getActivityBanner(component); } @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) @Override public Drawable getActivityBanner(Intent intent) throws NameNotFoundException { ResolveInfo ri = mPluginManager.resolveActivity(intent); if (null != ri) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(ri.resolvePackageName); return plugin.mResources.getDrawable(ri.activityInfo.banner); } return this.mHostPackageManager.getActivityBanner(intent); } @Override public Drawable getDefaultActivityIcon() { return this.mHostPackageManager.getDefaultActivityIcon(); } @Override public Drawable getApplicationIcon(ApplicationInfo info) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(info.packageName); if (null != plugin) { return plugin.mResources.getDrawable(info.icon); } return this.mHostPackageManager.getApplicationIcon(info); } @Override public Drawable getApplicationIcon(String packageName) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return plugin.mResources.getDrawable(plugin.mPackage.applicationInfo.icon); } return this.mHostPackageManager.getApplicationIcon(packageName); } @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) @Override public Drawable getApplicationBanner(ApplicationInfo info) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(info.packageName); if (null != plugin) { return plugin.mResources.getDrawable(info.banner); } return this.mHostPackageManager.getApplicationBanner(info); } @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) @Override public Drawable getApplicationBanner(String packageName) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return plugin.mResources.getDrawable(plugin.mPackage.applicationInfo.banner); } return this.mHostPackageManager.getApplicationBanner(packageName); } @Override public Drawable getActivityLogo(ComponentName component) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { return plugin.mResources.getDrawable(plugin.mActivityInfos.get(component).logo); } return this.mHostPackageManager.getActivityLogo(component); } @Override public Drawable getActivityLogo(Intent intent) throws NameNotFoundException { ResolveInfo ri = mPluginManager.resolveActivity(intent); if (null != ri) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(ri.resolvePackageName); return plugin.mResources.getDrawable(ri.activityInfo.logo); } return this.mHostPackageManager.getActivityLogo(intent); } @Override public Drawable getApplicationLogo(ApplicationInfo info) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(info.packageName); if (null != plugin) { return plugin.mResources.getDrawable(0 != info.logo ? info.logo : android.R.drawable.sym_def_app_icon); } return this.mHostPackageManager.getApplicationLogo(info); } @Override public Drawable getApplicationLogo(String packageName) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return plugin.mResources.getDrawable(0 != plugin.mPackage.applicationInfo.logo ? plugin.mPackage.applicationInfo.logo : android.R.drawable.sym_def_app_icon); } return this.mHostPackageManager.getApplicationLogo(packageName); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public Drawable getUserBadgedIcon(Drawable icon, UserHandle user) { return this.mHostPackageManager.getUserBadgedIcon(icon, user); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public Drawable getUserBadgeForDensity(UserHandle user, int density) { try { return Reflector.with(this.mHostPackageManager) .method("getUserBadgeForDensity", UserHandle.class, int.class) .call(user, density); } catch (Exception e) { throw new RuntimeException(e); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public Drawable getUserBadgedDrawableForDensity(Drawable drawable, UserHandle user, Rect badgeLocation, int badgeDensity) { return this.mHostPackageManager.getUserBadgedDrawableForDensity(drawable, user, badgeLocation, badgeDensity); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public CharSequence getUserBadgedLabel(CharSequence label, UserHandle user) { return this.mHostPackageManager.getUserBadgedLabel(label, user); } @Override public CharSequence getText(String packageName, int resid, ApplicationInfo appInfo) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return plugin.mResources.getText(resid); } return this.mHostPackageManager.getText(packageName, resid, appInfo); } @Override public XmlResourceParser getXml(String packageName, int resid, ApplicationInfo appInfo) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return plugin.mResources.getXml(resid); } return this.mHostPackageManager.getXml(packageName, resid, appInfo); } @Override public CharSequence getApplicationLabel(ApplicationInfo info) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(info.packageName); if (null != plugin) { try { return plugin.mResources.getText(info.labelRes); } catch (Resources.NotFoundException e) { // ignored. } } return this.mHostPackageManager.getApplicationLabel(info); } @Override public Resources getResourcesForActivity(ComponentName component) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component); if (null != plugin) { return plugin.mResources; } return this.mHostPackageManager.getResourcesForActivity(component); } @Override public Resources getResourcesForApplication(ApplicationInfo app) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(app.packageName); if (null != plugin) { return plugin.mResources; } return this.mHostPackageManager.getResourcesForApplication(app); } @Override public Resources getResourcesForApplication(String appPackageName) throws NameNotFoundException { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(appPackageName); if (null != plugin) { return plugin.mResources; } return this.mHostPackageManager.getResourcesForApplication(appPackageName); } @Override public void verifyPendingInstall(int id, int verificationCode) { this.mHostPackageManager.verifyPendingInstall(id, verificationCode); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, long millisecondsToDelay) { this.mHostPackageManager.extendVerificationTimeout(id, verificationCodeAtTimeout, millisecondsToDelay); } @Override public void setInstallerPackageName(String targetPackage, String installerPackageName) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(targetPackage); if (null != plugin) { return; } this.mHostPackageManager.setInstallerPackageName(targetPackage, installerPackageName); } @Override public String getInstallerPackageName(String packageName) { LoadedPlugin plugin = mPluginManager.getLoadedPlugin(packageName); if (null != plugin) { return mHostContext.getPackageName(); } return this.mHostPackageManager.getInstallerPackageName(packageName); } @Override public void addPackageToPreferred(String packageName) { this.mHostPackageManager.addPackageToPreferred(packageName); } @Override public void removePackageFromPreferred(String packageName) { this.mHostPackageManager.removePackageFromPreferred(packageName); } @Override public List<PackageInfo> getPreferredPackages(int flags) { return this.mHostPackageManager.getPreferredPackages(flags); } @Override public void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) { this.mHostPackageManager.addPreferredActivity(filter, match, set, activity); } @Override public void clearPackagePreferredActivities(String packageName) { this.mHostPackageManager.clearPackagePreferredActivities(packageName); } @Override public int getPreferredActivities(@NonNull List<IntentFilter> outFilters, @NonNull List<ComponentName> outActivities, String packageName) { return this.mHostPackageManager.getPreferredActivities(outFilters, outActivities, packageName); } @Override public void setComponentEnabledSetting(ComponentName component, int newState, int flags) { this.mHostPackageManager.setComponentEnabledSetting(component, newState, flags); } @Override public int getComponentEnabledSetting(ComponentName component) { return this.mHostPackageManager.getComponentEnabledSetting(component); } @Override public void setApplicationEnabledSetting(String packageName, int newState, int flags) { this.mHostPackageManager.setApplicationEnabledSetting(packageName, newState, flags); } @Override public int getApplicationEnabledSetting(String packageName) { return this.mHostPackageManager.getApplicationEnabledSetting(packageName); } @Override public boolean isSafeMode() { return this.mHostPackageManager.isSafeMode(); } @TargetApi(Build.VERSION_CODES.O) @Override public void setApplicationCategoryHint(@NonNull String packageName, int categoryHint) { this.mHostPackageManager.setApplicationCategoryHint(packageName, categoryHint); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public @NonNull PackageInstaller getPackageInstaller() { return this.mHostPackageManager.getPackageInstaller(); } @TargetApi(Build.VERSION_CODES.O) @Override public boolean canRequestPackageInstalls() { return this.mHostPackageManager.canRequestPackageInstalls(); } public Drawable loadItemIcon(PackageItemInfo itemInfo, ApplicationInfo appInfo) { if (itemInfo == null) { return null; } return itemInfo.loadIcon(this.mHostPackageManager); } } }
didi/VirtualAPK
CoreLibrary/src/main/java/com/didi/virtualapk/internal/LoadedPlugin.java
214,039
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cluster; import java.util.Random; import org.apache.ignite.internal.util.typedef.internal.SB; /** * Generator of default cluster tags. */ public class ClusterTagGenerator { /** Left part of cluster tag. */ public static String[] LEFT_PART = new String[] { "admiring", "adoring", "affectionate", "agitated", "amazing", "angry", "awesome", "beautiful", "blissful", "brave", "busy", "charming", "clever", "cool", "compassionate", "competent", "condescending", "confident", "cranky", "dazzling", "determined", "dreamy", "eager", "ecstatic", "elastic", "elated", "elegant", "eloquent", "epic", "exciting", "fervent", "festive", "flamboyant", "focused", "friendly", "frosty", "funny", "gallant", "gifted", "goofy", "gracious", "great", "happy", "hardcore", "heuristic", "hopeful", "hungry", "infallible", "inspiring", "interesting", "intelligent", "jolly", "jovial", "keen", "kind", "laughing", "loving", "lucid", "magical", "mystifying", "modest", "musing", "naughty", "nervous", "nice", "nifty", "nostalgic", "objective", "optimistic", "peaceful", "pedantic", "pensive", "practical", "priceless", "quirky", "quizzical", "recursing", "relaxed", "reverent", "romantic", "sad", "serene", "sharp", "silly", "sleepy", "stoic", "strange", "stupefied", "suspicious", "sweet", "tender", "thirsty", "trusting", "unruffled", "upbeat", "vibrant", "vigilant", "vigorous", "wizardly", "wonderful", "xenodochial", "youthful", "zealous", "zen" }; /** Right part of cluster tag. */ public static String[] RIGHT_PART = new String[] { // Muhammad ibn Jābir al-Ḥarrānī al-Battānī was a founding father of astronomy. https://en.wikipedia.org/wiki/Mu%E1%B8%A5ammad_ibn_J%C4%81bir_al-%E1%B8%A4arr%C4%81n%C4%AB_al-Batt%C4%81n%C4%AB "albattani", // Frances E. Allen, became the first female IBM Fellow in 1989. In 2006, she became the first female recipient of the ACM's Turing Award. https://en.wikipedia.org/wiki/Frances_E._Allen "allen", // June Almeida - Scottish virologist who took the first pictures of the rubella virus - https://en.wikipedia.org/wiki/June_Almeida "almeida", // Kathleen Antonelli, American computer programmer and one of the six original programmers of the ENIAC - https://en.wikipedia.org/wiki/Kathleen_Antonelli "antonelli", // Maria Gaetana Agnesi - Italian mathematician, philosopher, theologian and humanitarian. She was the first woman to write a mathematics handbook and the first woman appointed as a Mathematics Professor at a University. https://en.wikipedia.org/wiki/Maria_Gaetana_Agnesi "agnesi", // Archimedes was a physicist, engineer and mathematician who invented too many things to list them here. https://en.wikipedia.org/wiki/Archimedes "archimedes", // Maria Ardinghelli - Italian translator, mathematician and physicist - https://en.wikipedia.org/wiki/Maria_Ardinghelli "ardinghelli", // Aryabhata - Ancient Indian mathematician-astronomer during 476-550 CE https://en.wikipedia.org/wiki/Aryabhata "aryabhata", // Wanda Austin - Wanda Austin is the President and CEO of The Aerospace Corporation, a leading architect for the US security space programs. https://en.wikipedia.org/wiki/Wanda_Austin "austin", // Charles Babbage invented the concept of a programmable computer. https://en.wikipedia.org/wiki/Charles_Babbage. "babbage", // Stefan Banach - Polish mathematician, was one of the founders of modern functional analysis. https://en.wikipedia.org/wiki/Stefan_Banach "banach", // Buckaroo Banzai and his mentor Dr. Hikita perfectd the "oscillation overthruster", a device that allows one to pass through solid matter. - https://en.wikipedia.org/wiki/The_Adventures_of_Buckaroo_Banzai_Across_the_8th_Dimension "banzai", // John Bardeen co-invented the transistor - https://en.wikipedia.org/wiki/John_Bardeen "bardeen", // Jean Bartik, born Betty Jean Jennings, was one of the original programmers for the ENIAC computer. https://en.wikipedia.org/wiki/Jean_Bartik "bartik", // Laura Bassi, the world's first female professor https://en.wikipedia.org/wiki/Laura_Bassi "bassi", // Hugh Beaver, British engineer, founder of the Guinness Book of World Records https://en.wikipedia.org/wiki/Hugh_Beaver "beaver", // Alexander Graham Bell - an eminent Scottish-born scientist, inventor, engineer and innovator who is credited with inventing the first practical telephone - https://en.wikipedia.org/wiki/Alexander_Graham_Bell "bell", // Karl Friedrich Benz - a German automobile engineer. Inventor of the first practical motorcar. https://en.wikipedia.org/wiki/Karl_Benz "benz", // Homi J Bhabha - was an Indian nuclear physicist, founding director, and professor of physics at the Tata Institute of Fundamental Research. Colloquially known as "father of Indian nuclear programme"- https://en.wikipedia.org/wiki/Homi_J._Bhabha "bhabha", // Bhaskara II - Ancient Indian mathematician-astronomer whose work on calculus predates Newton and Leibniz by over half a millennium - https://en.wikipedia.org/wiki/Bh%C4%81skara_II#Calculus "bhaskara", // Sue Black - British computer scientist and campaigner. She has been instrumental in saving Bletchley Park, the site of World War II codebreaking - https://en.wikipedia.org/wiki/Sue_Black_(computer_scientist) "black", // Elizabeth Helen Blackburn - Australian-American Nobel laureate; best known for co-discovering telomerase. https://en.wikipedia.org/wiki/Elizabeth_Blackburn "blackburn", // Elizabeth Blackwell - American doctor and first American woman to receive a medical degree - https://en.wikipedia.org/wiki/Elizabeth_Blackwell "blackwell", // Niels Bohr is the father of quantum theory. https://en.wikipedia.org/wiki/Niels_Bohr. "bohr", // Kathleen Booth, she's credited with writing the first assembly language. https://en.wikipedia.org/wiki/Kathleen_Booth "booth", // Anita Borg - Anita Borg was the founding director of the Institute for Women and Technology (IWT). https://en.wikipedia.org/wiki/Anita_Borg "borg", // Satyendra Nath Bose - He provided the foundation for Bose–Einstein statistics and the theory of the Bose–Einstein condensate. - https://en.wikipedia.org/wiki/Satyendra_Nath_Bose "bose", // Katherine Louise Bouman is an imaging scientist and Assistant Professor of Computer Science at the California Institute of Technology. She researches computational methods for imaging, and developed an algorithm that made possible the picture first visualization of a black hole using the Event Horizon Telescope. - https://en.wikipedia.org/wiki/Katie_Bouman "bouman", // Evelyn Boyd Granville - She was one of the first African-American woman to receive a Ph.D. in mathematics; she earned it in 1949 from Yale University. https://en.wikipedia.org/wiki/Evelyn_Boyd_Granville "boyd", // Brahmagupta - Ancient Indian mathematician during 598-670 CE who gave rules to compute with zero - https://en.wikipedia.org/wiki/Brahmagupta#Zero "brahmagupta", // Walter Houser Brattain co-invented the transistor - https://en.wikipedia.org/wiki/Walter_Houser_Brattain "brattain", // Emmett Brown invented time travel. https://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff) "brown", // Linda Brown Buck - American biologist and Nobel laureate best known for her genetic and molecular analyses of the mechanisms of smell. https://en.wikipedia.org/wiki/Linda_B._Buck "buck", // Dame Susan Jocelyn Bell Burnell - Northern Irish astrophysicist who discovered radio pulsars and was the first to analyse them. https://en.wikipedia.org/wiki/Jocelyn_Bell_Burnell "burnell", // Annie Jump Cannon - pioneering female astronomer who classified hundreds of thousands of stars and created the system we use to understand stars today. https://en.wikipedia.org/wiki/Annie_Jump_Cannon "cannon", // Rachel Carson - American marine biologist and conservationist, her book Silent Spring and other writings are credited with advancing the global environmental movement. https://en.wikipedia.org/wiki/Rachel_Carson "carson", // Dame Mary Lucy Cartwright - British mathematician who was one of the first to study what is now known as chaos theory. Also known for Cartwright's theorem which finds applications in signal processing. https://en.wikipedia.org/wiki/Mary_Cartwright "cartwright", // Vinton Gray Cerf - American Internet pioneer, recognised as one of "the fathers of the Internet". With Robert Elliot Kahn, he designed TCP and IP, the primary data communication protocols of the Internet and other computer networks. https://en.wikipedia.org/wiki/Vint_Cerf "cerf", // Subrahmanyan Chandrasekhar - Astrophysicist known for his mathematical theory on different stages and evolution in structures of the stars. He has won nobel prize for physics - https://en.wikipedia.org/wiki/Subrahmanyan_Chandrasekhar "chandrasekhar", // Sergey Alexeyevich Chaplygin (Russian: Серге́й Алексе́евич Чаплы́гин; April 5, 1869 – October 8, 1942) was a Russian and Soviet physicist, mathematician, and mechanical engineer. He is known for mathematical formulas such as Chaplygin's equation and for a hypothetical substance in cosmology called Chaplygin gas, named after him. https://en.wikipedia.org/wiki/Sergey_Chaplygin "chaplygin", // Émilie du Châtelet - French natural philosopher, mathematician, physicist, and author during the early 1730s, known for her translation of and commentary on Isaac Newton's book Principia containing basic laws of physics. https://en.wikipedia.org/wiki/%C3%89milie_du_Ch%C3%A2telet "chatelet", // Asima Chatterjee was an Indian organic chemist noted for her research on vinca alkaloids, development of drugs for treatment of epilepsy and malaria - https://en.wikipedia.org/wiki/Asima_Chatterjee "chatterjee", // Pafnuty Chebyshev - Russian mathematician. He is known fo his works on probability, statistics, mechanics, analytical geometry and number theory https://en.wikipedia.org/wiki/Pafnuty_Chebyshev "chebyshev", // Bram Cohen - American computer programmer and author of the BitTorrent peer-to-peer protocol. https://en.wikipedia.org/wiki/Bram_Cohen "cohen", // David Lee Chaum - American computer scientist and cryptographer. Known for his seminal contributions in the field of anonymous communication. https://en.wikipedia.org/wiki/David_Chaum "chaum", // Joan Clarke - Bletchley Park code breaker during the Second World War who pioneered techniques that remained top secret for decades. Also an accomplished numismatist https://en.wikipedia.org/wiki/Joan_Clarke "clarke", // Jane Colden - American botanist widely considered the first female American botanist - https://en.wikipedia.org/wiki/Jane_Colden "colden", // Gerty Theresa Cori - American biochemist who became the third woman—and first American woman—to win a Nobel Prize in science, and the first woman to be awarded the Nobel Prize in Physiology or Medicine. Cori was born in Prague. https://en.wikipedia.org/wiki/Gerty_Cori "cori", // Seymour Roger Cray was an American electrical engineer and supercomputer architect who designed a series of computers that were the fastest in the world for decades. https://en.wikipedia.org/wiki/Seymour_Cray "cray", // This entry reflects a husband and wife team who worked together: // Joan Curran was a Welsh scientist who developed radar and invented chaff, a radar countermeasure. https://en.wikipedia.org/wiki/Joan_Curran // Samuel Curran was an Irish physicist who worked alongside his wife during WWII and invented the proximity fuse. https://en.wikipedia.org/wiki/Samuel_Curran "curran", // Marie Curie discovered radioactivity. https://en.wikipedia.org/wiki/Marie_Curie. "curie", // Charles Darwin established the principles of natural evolution. https://en.wikipedia.org/wiki/Charles_Darwin. "darwin", // Leonardo Da Vinci invented too many things to list here. https://en.wikipedia.org/wiki/Leonardo_da_Vinci. "davinci", // A. K. (Alexander Keewatin) Dewdney, Canadian mathematician, computer scientist, author and filmmaker. Contributor to Scientific American's "Computer Recreations" from 1984 to 1991. Author of Core War (program), The Planiverse, The Armchair Universe, The Magic Machine, The New Turing Omnibus, and more. https://en.wikipedia.org/wiki/Alexander_Dewdney "dewdney", // Satish Dhawan - Indian mathematician and aerospace engineer, known for leading the successful and indigenous development of the Indian space programme. https://en.wikipedia.org/wiki/Satish_Dhawan "dhawan", // Bailey Whitfield Diffie - American cryptographer and one of the pioneers of public-key cryptography. https://en.wikipedia.org/wiki/Whitfield_Diffie "diffie", // Edsger Wybe Dijkstra was a Dutch computer scientist and mathematical scientist. https://en.wikipedia.org/wiki/Edsger_W._Dijkstra. "dijkstra", // Paul Adrien Maurice Dirac - English theoretical physicist who made fundamental contributions to the early development of both quantum mechanics and quantum electrodynamics. https://en.wikipedia.org/wiki/Paul_Dirac "dirac", // Agnes Meyer Driscoll - American cryptanalyst during World Wars I and II who successfully cryptanalysed a number of Japanese ciphers. She was also the co-developer of one of the cipher machines of the US Navy, the CM. https://en.wikipedia.org/wiki/Agnes_Meyer_Driscoll "driscoll", // Donna Dubinsky - played an integral role in the development of personal digital assistants (PDAs) serving as CEO of Palm, Inc. and co-founding Handspring. https://en.wikipedia.org/wiki/Donna_Dubinsky "dubinsky", // Annie Easley - She was a leading member of the team which developed software for the Centaur rocket stage and one of the first African-Americans in her field. https://en.wikipedia.org/wiki/Annie_Easley "easley", // Thomas Alva Edison, prolific inventor https://en.wikipedia.org/wiki/Thomas_Edison "edison", // Albert Einstein invented the general theory of relativity. https://en.wikipedia.org/wiki/Albert_Einstein "einstein", // Alexandra Asanovna Elbakyan (Russian: Алекса́ндра Аса́новна Элбакя́н) is a Kazakhstani graduate student, computer programmer, internet pirate in hiding, and the creator of the site Sci-Hub. Nature has listed her in 2016 in the top ten people that mattered in science, and Ars Technica has compared her to Aaron Swartz. - https://en.wikipedia.org/wiki/Alexandra_Elbakyan "elbakyan", // Taher A. ElGamal - Egyptian cryptographer best known for the ElGamal discrete log cryptosystem and the ElGamal digital signature scheme. https://en.wikipedia.org/wiki/Taher_Elgamal "elgamal", // Gertrude Elion - American biochemist, pharmacologist and the 1988 recipient of the Nobel Prize in Medicine - https://en.wikipedia.org/wiki/Gertrude_Elion "elion", // James Henry Ellis - British engineer and cryptographer employed by the GCHQ. Best known for conceiving for the first time, the idea of public-key cryptography. https://en.wikipedia.org/wiki/James_H._Ellis "ellis", // Douglas Engelbart gave the mother of all demos: https://en.wikipedia.org/wiki/Douglas_Engelbart "engelbart", // Euclid invented geometry. https://en.wikipedia.org/wiki/Euclid "euclid", // Leonhard Euler invented large parts of modern mathematics. https://de.wikipedia.org/wiki/Leonhard_Euler "euler", // Michael Faraday - British scientist who contributed to the study of electromagnetism and electrochemistry. https://en.wikipedia.org/wiki/Michael_Faraday "faraday", // Horst Feistel - German-born American cryptographer who was one of the earliest non-government researchers to study the design and theory of block ciphers. Co-developer of DES and Lucifer. Feistel networks, a symmetric structure used in the construction of block ciphers are named after him. https://en.wikipedia.org/wiki/Horst_Feistel "feistel", // Pierre de Fermat pioneered several aspects of modern mathematics. https://en.wikipedia.org/wiki/Pierre_de_Fermat "fermat", // Enrico Fermi invented the first nuclear reactor. https://en.wikipedia.org/wiki/Enrico_Fermi. "fermi", // Richard Feynman was a key contributor to quantum mechanics and particle physics. https://en.wikipedia.org/wiki/Richard_Feynman "feynman", // Benjamin Franklin is famous for his experiments in electricity and the invention of the lightning rod. "franklin", // Yuri Alekseyevich Gagarin - Soviet pilot and cosmonaut, best known as the first human to journey into outer space. https://en.wikipedia.org/wiki/Yuri_Gagarin "gagarin", // Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth. https://en.wikipedia.org/wiki/Galileo_Galilei "galileo", // Évariste Galois - French mathematician whose work laid the foundations of Galois theory and group theory, two major branches of abstract algebra, and the subfield of Galois connections, all while still in his late teens. https://en.wikipedia.org/wiki/%C3%89variste_Galois "galois", // Kadambini Ganguly - Indian physician, known for being the first South Asian female physician, trained in western medicine, to graduate in South Asia. https://en.wikipedia.org/wiki/Kadambini_Ganguly "ganguly", // William Henry "Bill" Gates III is an American business magnate, philanthropist, investor, computer programmer, and inventor. https://en.wikipedia.org/wiki/Bill_Gates "gates", // Johann Carl Friedrich Gauss - German mathematician who made significant contributions to many fields, including number theory, algebra, statistics, analysis, differential geometry, geodesy, geophysics, mechanics, electrostatics, magnetic fields, astronomy, matrix theory, and optics. https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss "gauss", // Marie-Sophie Germain - French mathematician, physicist and philosopher. Known for her work on elasticity theory, number theory and philosophy. https://en.wikipedia.org/wiki/Sophie_Germain "germain", // Adele Goldberg, was one of the designers and developers of the Smalltalk language. https://en.wikipedia.org/wiki/Adele_Goldberg_(computer_scientist) "goldberg", // Adele Goldstine, born Adele Katz, wrote the complete technical description for the first electronic digital computer, ENIAC. https://en.wikipedia.org/wiki/Adele_Goldstine "goldstine", // Shafi Goldwasser is a computer scientist known for creating theoretical foundations of modern cryptography. Winner of 2012 ACM Turing Award. https://en.wikipedia.org/wiki/Shafi_Goldwasser "goldwasser", // James Golick, all around gangster. "golick", // Jane Goodall - British primatologist, ethologist, and anthropologist who is considered to be the world's foremost expert on chimpanzees - https://en.wikipedia.org/wiki/Jane_Goodall "goodall", // Stephen Jay Gould was was an American paleontologist, evolutionary biologist, and historian of science. He is most famous for the theory of punctuated equilibrium - https://en.wikipedia.org/wiki/Stephen_Jay_Gould "gould", // Carolyn Widney Greider - American molecular biologist and joint winner of the 2009 Nobel Prize for Physiology or Medicine for the discovery of telomerase. https://en.wikipedia.org/wiki/Carol_W._Greider "greider", // Alexander Grothendieck - German-born French mathematician who became a leading figure in the creation of modern algebraic geometry. https://en.wikipedia.org/wiki/Alexander_Grothendieck "grothendieck", // Lois Haibt - American computer scientist, part of the team at IBM that developed FORTRAN - https://en.wikipedia.org/wiki/Lois_Haibt "haibt", // Margaret Hamilton - Director of the Software Engineering Division of the MIT Instrumentation Laboratory, which developed on-board flight software for the Apollo space program. https://en.wikipedia.org/wiki/Margaret_Hamilton_(scientist) "hamilton", // Caroline Harriet Haslett - English electrical engineer, electricity industry administrator and champion of women's rights. Co-author of British Standard 1363 that specifies AC power plugs and sockets used across the United Kingdom (which is widely considered as one of the safest designs). https://en.wikipedia.org/wiki/Caroline_Haslett "haslett", // Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. https://en.wikipedia.org/wiki/Stephen_Hawking "hawking", // Martin Edward Hellman - American cryptologist, best known for his invention of public-key cryptography in co-operation with Whitfield Diffie and Ralph Merkle. https://en.wikipedia.org/wiki/Martin_Hellman "hellman", // Werner Heisenberg was a founding father of quantum mechanics. https://en.wikipedia.org/wiki/Werner_Heisenberg "heisenberg", // Grete Hermann was a German philosopher noted for her philosophical work on the foundations of quantum mechanics. https://en.wikipedia.org/wiki/Grete_Hermann "hermann", // Caroline Lucretia Herschel - German astronomer and discoverer of several comets. https://en.wikipedia.org/wiki/Caroline_Herschel "herschel", // Heinrich Rudolf Hertz - German physicist who first conclusively proved the existence of the electromagnetic waves. https://en.wikipedia.org/wiki/Heinrich_Hertz "hertz", // Jaroslav Heyrovský was the inventor of the polarographic method, father of the electroanalytical method, and recipient of the Nobel Prize in 1959. His main field of work was polarography. https://en.wikipedia.org/wiki/Jaroslav_Heyrovsk%C3%BD "heyrovsky", // Dorothy Hodgkin was a British biochemist, credited with the development of protein crystallography. She was awarded the Nobel Prize in Chemistry in 1964. https://en.wikipedia.org/wiki/Dorothy_Hodgkin "hodgkin", // Douglas R. Hofstadter is an American professor of cognitive science and author of the Pulitzer Prize and American Book Award-winning work Goedel, Escher, Bach: An Eternal Golden Braid in 1979. A mind-bending work which coined Hofstadter's Law: "It always takes longer than you expect, even when you take into account Hofstadter's Law." https://en.wikipedia.org/wiki/Douglas_Hofstadter "hofstadter", // Erna Schneider Hoover revolutionized modern communication by inventing a computerized telephone switching method. https://en.wikipedia.org/wiki/Erna_Schneider_Hoover "hoover", // Grace Hopper developed the first compiler for a computer programming language and is credited with popularizing the term "debugging" for fixing computer glitches. https://en.wikipedia.org/wiki/Grace_Hopper "hopper", // Frances Hugle, she was an American scientist, engineer, and inventor who contributed to the understanding of semiconductors, integrated circuitry, and the unique electrical principles of microscopic materials. https://en.wikipedia.org/wiki/Frances_Hugle "hugle", // Hypatia - Greek Alexandrine Neoplatonist philosopher in Egypt who was one of the earliest mothers of mathematics - https://en.wikipedia.org/wiki/Hypatia "hypatia", // Teruko Ishizaka - Japanese scientist and immunologist who co-discovered the antibody class Immunoglobulin E. https://en.wikipedia.org/wiki/Teruko_Ishizaka "ishizaka", // Mary Jackson, American mathematician and aerospace engineer who earned the highest title within NASA's engineering department - https://en.wikipedia.org/wiki/Mary_Jackson_(engineer) "jackson", // Yeong-Sil Jang was a Korean scientist and astronomer during the Joseon Dynasty; he invented the first metal printing press and water gauge. https://en.wikipedia.org/wiki/Jang_Yeong-sil "jang", // Betty Jennings - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Jean_Bartik "jennings", // Mary Lou Jepsen, was the founder and chief technology officer of One Laptop Per Child (OLPC), and the founder of Pixel Qi. https://en.wikipedia.org/wiki/Mary_Lou_Jepsen "jepsen", // Katherine Coleman Goble Johnson - American physicist and mathematician contributed to the NASA. https://en.wikipedia.org/wiki/Katherine_Johnson "johnson", // Irène Joliot-Curie - French scientist who was awarded the Nobel Prize for Chemistry in 1935. Daughter of Marie and Pierre Curie. https://en.wikipedia.org/wiki/Ir%C3%A8ne_Joliot-Curie "joliot", // Karen Spärck Jones came up with the concept of inverse document frequency, which is used in most search engines today. https://en.wikipedia.org/wiki/Karen_Sp%C3%A4rck_Jones "jones", // A. P. J. Abdul Kalam - is an Indian scientist aka Missile Man of India for his work on the development of ballistic missile and launch vehicle technology - https://en.wikipedia.org/wiki/A._P._J._Abdul_Kalam "kalam", // Sergey Petrovich Kapitsa (Russian: Серге́й Петро́вич Капи́ца; 14 February 1928 – 14 August 2012) was a Russian physicist and demographer. He was best known as host of the popular and long-running Russian scientific TV show, Evident, but Incredible. His father was the Nobel laureate Soviet-era physicist Pyotr Kapitsa, and his brother was the geographer and Antarctic explorer Andrey Kapitsa. - https://en.wikipedia.org/wiki/Sergey_Kapitsa "kapitsa", // Susan Kare, created the icons and many of the interface elements for the original Apple Macintosh in the 1980s, and was an original employee of NeXT, working as the Creative Director. https://en.wikipedia.org/wiki/Susan_Kare "kare", // Mstislav Keldysh - a Soviet scientist in the field of mathematics and mechanics, academician of the USSR Academy of Sciences (1946), President of the USSR Academy of Sciences (1961–1975), three times Hero of Socialist Labor (1956, 1961, 1971), fellow of the Royal Society of Edinburgh (1968). https://en.wikipedia.org/wiki/Mstislav_Keldysh "keldysh", // Mary Kenneth Keller, Sister Mary Kenneth Keller became the first American woman to earn a PhD in Computer Science in 1965. https://en.wikipedia.org/wiki/Mary_Kenneth_Keller "keller", // Johannes Kepler, German astronomer known for his three laws of planetary motion - https://en.wikipedia.org/wiki/Johannes_Kepler "kepler", // Omar Khayyam - Persian mathematician, astronomer and poet. Known for his work on the classification and solution of cubic equations, for his contribution to the understanding of Euclid's fifth postulate and for computing the length of a year very accurately. https://en.wikipedia.org/wiki/Omar_Khayyam "khayyam", // Har Gobind Khorana - Indian-American biochemist who shared the 1968 Nobel Prize for Physiology - https://en.wikipedia.org/wiki/Har_Gobind_Khorana "khorana", // Jack Kilby invented silicone integrated circuits and gave Silicon Valley its name. - https://en.wikipedia.org/wiki/Jack_Kilby "kilby", // Maria Kirch - German astronomer and first woman to discover a comet - https://en.wikipedia.org/wiki/Maria_Margarethe_Kirch "kirch", // Donald Knuth - American computer scientist, author of "The Art of Computer Programming" and creator of the TeX typesetting system. https://en.wikipedia.org/wiki/Donald_Knuth "knuth", // Sophie Kowalevski - Russian mathematician responsible for important original contributions to analysis, differential equations and mechanics - https://en.wikipedia.org/wiki/Sofia_Kovalevskaya "kowalevski", // Marie-Jeanne de Lalande - French astronomer, mathematician and cataloguer of stars - https://en.wikipedia.org/wiki/Marie-Jeanne_de_Lalande "lalande", // Hedy Lamarr - Actress and inventor. The principles of her work are now incorporated into modern Wi-Fi, CDMA and Bluetooth technology. https://en.wikipedia.org/wiki/Hedy_Lamarr "lamarr", // Leslie B. Lamport - American computer scientist. Lamport is best known for his seminal work in distributed systems and was the winner of the 2013 Turing Award. https://en.wikipedia.org/wiki/Leslie_Lamport "lamport", // Mary Leakey - British paleoanthropologist who discovered the first fossilized Proconsul skull - https://en.wikipedia.org/wiki/Mary_Leakey "leakey", // Henrietta Swan Leavitt - she was an American astronomer who discovered the relation between the luminosity and the period of Cepheid variable stars. https://en.wikipedia.org/wiki/Henrietta_Swan_Leavitt "leavitt", // Esther Miriam Zimmer Lederberg - American microbiologist and a pioneer of bacterial genetics. https://en.wikipedia.org/wiki/Esther_Lederberg "lederberg", // Inge Lehmann - Danish seismologist and geophysicist. Known for discovering in 1936 that the Earth has a solid inner core inside a molten outer core. https://en.wikipedia.org/wiki/Inge_Lehmann "lehmann", // Daniel Lewin - Mathematician, Akamai co-founder, soldier, 9/11 victim-- Developed optimization techniques for routing traffic on the internet. Died attempting to stop the 9-11 hijackers. https://en.wikipedia.org/wiki/Daniel_Lewin "lewin", // Ruth Lichterman - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Ruth_Teitelbaum "lichterman", // Barbara Liskov - co-developed the Liskov substitution principle. Liskov was also the winner of the Turing Prize in 2008. - https://en.wikipedia.org/wiki/Barbara_Liskov "liskov", // Ada Lovelace invented the first algorithm. https://en.wikipedia.org/wiki/Ada_Lovelace (thanks James Turnbull) "lovelace", // Auguste and Louis Lumière - the first filmmakers in history - https://en.wikipedia.org/wiki/Auguste_and_Louis_Lumi%C3%A8re "lumiere", // Mahavira - Ancient Indian mathematician during 9th century AD who discovered basic algebraic identities - https://en.wikipedia.org/wiki/Mah%C4%81v%C4%ABra_(mathematician) "mahavira", // Lynn Margulis (b. Lynn Petra Alexander) - an American evolutionary theorist and biologist, science author, educator, and popularizer, and was the primary modern proponent for the significance of symbiosis in evolution. - https://en.wikipedia.org/wiki/Lynn_Margulis "margulis", // Yukihiro Matsumoto - Japanese computer scientist and software programmer best known as the chief designer of the Ruby programming language. https://en.wikipedia.org/wiki/Yukihiro_Matsumoto "matsumoto", // James Clerk Maxwell - Scottish physicist, best known for his formulation of electromagnetic theory. https://en.wikipedia.org/wiki/James_Clerk_Maxwell "maxwell", // Maria Mayer - American theoretical physicist and Nobel laureate in Physics for proposing the nuclear shell model of the atomic nucleus - https://en.wikipedia.org/wiki/Maria_Mayer "mayer", // John McCarthy invented LISP: https://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist) "mccarthy", // Barbara McClintock - a distinguished American cytogeneticist, 1983 Nobel Laureate in Physiology or Medicine for discovering transposons. https://en.wikipedia.org/wiki/Barbara_McClintock "mcclintock", // Anne Laura Dorinthea McLaren - British developmental biologist whose work helped lead to human in-vitro fertilisation. https://en.wikipedia.org/wiki/Anne_McLaren "mclaren", // Malcolm McLean invented the modern shipping container: https://en.wikipedia.org/wiki/Malcom_McLean "mclean", // Kay McNulty - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Kathleen_Antonelli "mcnulty", // Gregor Johann Mendel - Czech scientist and founder of genetics. https://en.wikipedia.org/wiki/Gregor_Mendel "mendel", // Dmitri Mendeleev - a chemist and inventor. He formulated the Periodic Law, created a farsighted version of the periodic table of elements, and used it to correct the properties of some already discovered elements and also to predict the properties of eight elements yet to be discovered. https://en.wikipedia.org/wiki/Dmitri_Mendeleev "mendeleev", // Lise Meitner - Austrian/Swedish physicist who was involved in the discovery of nuclear fission. The element meitnerium is named after her - https://en.wikipedia.org/wiki/Lise_Meitner "meitner", // Carla Meninsky, was the game designer and programmer for Atari 2600 games Dodge 'Em and Warlords. https://en.wikipedia.org/wiki/Carla_Meninsky "meninsky", // Ralph C. Merkle - American computer scientist, known for devising Merkle's puzzles - one of the very first schemes for public-key cryptography. Also, inventor of Merkle trees and co-inventor of the Merkle-Damgård construction for building collision-resistant cryptographic hash functions and the Merkle-Hellman knapsack cryptosystem. https://en.wikipedia.org/wiki/Ralph_Merkle "merkle", // Johanna Mestorf - German prehistoric archaeologist and first female museum director in Germany - https://en.wikipedia.org/wiki/Johanna_Mestorf "mestorf", // Marvin Minsky - Pioneer in Artificial Intelligence, co-founder of the MIT's AI Lab, won the Turing Award in 1969. https://en.wikipedia.org/wiki/Marvin_Minsky "minsky", // Maryam Mirzakhani - an Iranian mathematician and the first woman to win the Fields Medal. https://en.wikipedia.org/wiki/Maryam_Mirzakhani "mirzakhani", // Gordon Earle Moore - American engineer, Silicon Valley founding father, author of Moore's law. https://en.wikipedia.org/wiki/Gordon_Moore "moore", // Samuel Morse - contributed to the invention of a single-wire telegraph system based on European telegraphs and was a co-developer of the Morse code - https://en.wikipedia.org/wiki/Samuel_Morse "morse", // Ian Murdock - founder of the Debian project - https://en.wikipedia.org/wiki/Ian_Murdock "murdock", // May-Britt Moser - Nobel prize winner neuroscientist who contributed to the discovery of grid cells in the brain. https://en.wikipedia.org/wiki/May-Britt_Moser "moser", // John Napier of Merchiston - Scottish landowner known as an astronomer, mathematician and physicist. Best known for his discovery of logarithms. https://en.wikipedia.org/wiki/John_Napier "napier", // John Forbes Nash, Jr. - American mathematician who made fundamental contributions to game theory, differential geometry, and the study of partial differential equations. https://en.wikipedia.org/wiki/John_Forbes_Nash_Jr. "nash", // John von Neumann - todays computer architectures are based on the von Neumann architecture. https://en.wikipedia.org/wiki/Von_Neumann_architecture "neumann", // Isaac Newton invented classic mechanics and modern optics. https://en.wikipedia.org/wiki/Isaac_Newton "newton", // Florence Nightingale, more prominently known as a nurse, was also the first female member of the Royal Statistical Society and a pioneer in statistical graphics https://en.wikipedia.org/wiki/Florence_Nightingale#Statistics_and_sanitary_reform "nightingale", // Alfred Nobel - a Swedish chemist, engineer, innovator, and armaments manufacturer (inventor of dynamite) - https://en.wikipedia.org/wiki/Alfred_Nobel "nobel", // Emmy Noether, German mathematician. Noether's Theorem is named after her. https://en.wikipedia.org/wiki/Emmy_Noether "noether", // Poppy Northcutt. Poppy Northcutt was the first woman to work as part of NASA’s Mission Control. http://www.businessinsider.com/poppy-northcutt-helped-apollo-astronauts-2014-12?op=1 "northcutt", // Robert Noyce invented silicone integrated circuits and gave Silicon Valley its name. - https://en.wikipedia.org/wiki/Robert_Noyce "noyce", // Panini - Ancient Indian linguist and grammarian from 4th century CE who worked on the world's first formal system - https://en.wikipedia.org/wiki/P%C4%81%E1%B9%87ini#Comparison_with_modern_formal_systems "panini", // Ambroise Pare invented modern surgery. https://en.wikipedia.org/wiki/Ambroise_Par%C3%A9 "pare", // Blaise Pascal, French mathematician, physicist, and inventor - https://en.wikipedia.org/wiki/Blaise_Pascal "pascal", // Louis Pasteur discovered vaccination, fermentation and pasteurization. https://en.wikipedia.org/wiki/Louis_Pasteur. "pasteur", // Cecilia Payne-Gaposchkin was an astronomer and astrophysicist who, in 1925, proposed in her Ph.D. thesis an explanation for the composition of stars in terms of the relative abundances of hydrogen and helium. https://en.wikipedia.org/wiki/Cecilia_Payne-Gaposchkin "payne", // Radia Perlman is a software designer and network engineer and most famous for her invention of the spanning-tree protocol (STP). https://en.wikipedia.org/wiki/Radia_Perlman "perlman", // Rob Pike was a key contributor to Unix, Plan 9, the X graphic system, utf-8, and the Go programming language. https://en.wikipedia.org/wiki/Rob_Pike "pike", // Henri Poincaré made fundamental contributions in several fields of mathematics. https://en.wikipedia.org/wiki/Henri_Poincar%C3%A9 "poincare", // Laura Poitras is a director and producer whose work, made possible by open source crypto tools, advances the causes of truth and freedom of information by reporting disclosures by whistleblowers such as Edward Snowden. https://en.wikipedia.org/wiki/Laura_Poitras "poitras", // Tat’yana Avenirovna Proskuriakova (Russian: Татья́на Авени́ровна Проскуряко́ва) (January 23 [O.S. January 10] 1909 – August 30, 1985) was a Russian-American Mayanist scholar and archaeologist who contributed significantly to the deciphering of Maya hieroglyphs, the writing system of the pre-Columbian Maya civilization of Mesoamerica. https://en.wikipedia.org/wiki/Tatiana_Proskouriakoff "proskuriakova", // Claudius Ptolemy - a Greco-Egyptian writer of Alexandria, known as a mathematician, astronomer, geographer, astrologer, and poet of a single epigram in the Greek Anthology - https://en.wikipedia.org/wiki/Ptolemy "ptolemy", // C. V. Raman - Indian physicist who won the Nobel Prize in 1930 for proposing the Raman effect. - https://en.wikipedia.org/wiki/C._V._Raman "raman", // Srinivasa Ramanujan - Indian mathematician and autodidact who made extraordinary contributions to mathematical analysis, number theory, infinite series, and continued fractions. - https://en.wikipedia.org/wiki/Srinivasa_Ramanujan "ramanujan", // Sally Kristen Ride was an American physicist and astronaut. She was the first American woman in space, and the youngest American astronaut. https://en.wikipedia.org/wiki/Sally_Ride "ride", // Rita Levi-Montalcini - Won Nobel Prize in Physiology or Medicine jointly with colleague Stanley Cohen for the discovery of nerve growth factor (https://en.wikipedia.org/wiki/Rita_Levi-Montalcini) "montalcini", // Dennis Ritchie - co-creator of UNIX and the C programming language. - https://en.wikipedia.org/wiki/Dennis_Ritchie "ritchie", // Ida Rhodes - American pioneer in computer programming, designed the first computer used for Social Security. https://en.wikipedia.org/wiki/Ida_Rhodes "rhodes", // Julia Hall Bowman Robinson - American mathematician renowned for her contributions to the fields of computability theory and computational complexity theory. https://en.wikipedia.org/wiki/Julia_Robinson "robinson", // Wilhelm Conrad Röntgen - German physicist who was awarded the first Nobel Prize in Physics in 1901 for the discovery of X-rays (Röntgen rays). https://en.wikipedia.org/wiki/Wilhelm_R%C3%B6ntgen "roentgen", // Rosalind Franklin - British biophysicist and X-ray crystallographer whose research was critical to the understanding of DNA - https://en.wikipedia.org/wiki/Rosalind_Franklin "rosalind", // Vera Rubin - American astronomer who pioneered work on galaxy rotation rates. https://en.wikipedia.org/wiki/Vera_Rubin "rubin", // Meghnad Saha - Indian astrophysicist best known for his development of the Saha equation, used to describe chemical and physical conditions in stars - https://en.wikipedia.org/wiki/Meghnad_Saha "saha", // Jean E. Sammet developed FORMAC, the first widely used computer language for symbolic manipulation of mathematical formulas. https://en.wikipedia.org/wiki/Jean_E._Sammet "sammet", // Mildred Sanderson - American mathematician best known for Sanderson's theorem concerning modular invariants. https://en.wikipedia.org/wiki/Mildred_Sanderson "sanderson", // Satoshi Nakamoto is the name used by the unknown person or group of people who developed bitcoin, authored the bitcoin white paper, and created and deployed bitcoin's original reference implementation. https://en.wikipedia.org/wiki/Satoshi_Nakamoto "satoshi", // Adi Shamir - Israeli cryptographer whose numerous inventions and contributions to cryptography include the Ferge Fiat Shamir identification scheme, the Rivest Shamir Adleman (RSA) public-key cryptosystem, the Shamir's secret sharing scheme, the breaking of the Merkle-Hellman cryptosystem, the TWINKLE and TWIRL factoring devices and the discovery of differential cryptanalysis (with Eli Biham). https://en.wikipedia.org/wiki/Adi_Shamir "shamir", // Claude Shannon - The father of information theory and founder of digital circuit design theory. (https://en.wikipedia.org/wiki/Claude_Shannon) "shannon", // Carol Shaw - Originally an Atari employee, Carol Shaw is said to be the first female video game designer. https://en.wikipedia.org/wiki/Carol_Shaw_(video_game_designer) "shaw", // Dame Stephanie "Steve" Shirley - Founded a software company in 1962 employing women working from home. https://en.wikipedia.org/wiki/Steve_Shirley "shirley", // William Shockley co-invented the transistor - https://en.wikipedia.org/wiki/William_Shockley "shockley", // Lina Solomonovna Stern (or Shtern; Russian: Лина Соломоновна Штерн; 26 August 1878 – 7 March 1968) was a Soviet biochemist, physiologist and humanist whose medical discoveries saved thousands of lives at the fronts of World War II. She is best known for her pioneering work on blood–brain barrier, which she described as hemato-encephalic barrier in 1921. https://en.wikipedia.org/wiki/Lina_Stern "shtern", // Françoise Barré-Sinoussi - French virologist and Nobel Prize Laureate in Physiology or Medicine; her work was fundamental in identifying HIV as the cause of AIDS. https://en.wikipedia.org/wiki/Fran%C3%A7oise_Barr%C3%A9-Sinoussi "sinoussi", // Betty Snyder - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Betty_Holberton "snyder", // Cynthia Solomon - Pioneer in the fields of artificial intelligence, computer science and educational computing. Known for creation of Logo, an educational programming language. https://en.wikipedia.org/wiki/Cynthia_Solomon "solomon", // Frances Spence - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Frances_Spence "spence", // Richard Matthew Stallman - the founder of the Free Software movement, the GNU project, the Free Software Foundation, and the League for Programming Freedom. He also invented the concept of copyleft to protect the ideals of this movement, and enshrined this concept in the widely-used GPL (General Public License) for software. https://en.wikiquote.org/wiki/Richard_Stallman "stallman", // Michael Stonebraker is a database research pioneer and architect of Ingres, Postgres, VoltDB and SciDB. Winner of 2014 ACM Turing Award. https://en.wikipedia.org/wiki/Michael_Stonebraker "stonebraker", // Ivan Edward Sutherland - American computer scientist and Internet pioneer, widely regarded as the father of computer graphics. https://en.wikipedia.org/wiki/Ivan_Sutherland "sutherland", // Janese Swanson (with others) developed the first of the Carmen Sandiego games. She went on to found Girl Tech. https://en.wikipedia.org/wiki/Janese_Swanson "swanson", // Aaron Swartz was influential in creating RSS, Markdown, Creative Commons, Reddit, and much of the internet as we know it today. He was devoted to freedom of information on the web. https://en.wikiquote.org/wiki/Aaron_Swartz "swartz", // Bertha Swirles was a theoretical physicist who made a number of contributions to early quantum theory. https://en.wikipedia.org/wiki/Bertha_Swirles "swirles", // Helen Brooke Taussig - American cardiologist and founder of the field of paediatric cardiology. https://en.wikipedia.org/wiki/Helen_B._Taussig "taussig", // Valentina Tereshkova is a Russian engineer, cosmonaut and politician. She was the first woman to fly to space in 1963. In 2013, at the age of 76, she offered to go on a one-way mission to Mars. https://en.wikipedia.org/wiki/Valentina_Tereshkova "tereshkova", // Nikola Tesla invented the AC electric system and every gadget ever used by a James Bond villain. https://en.wikipedia.org/wiki/Nikola_Tesla "tesla", // Marie Tharp - American geologist and oceanic cartographer who co-created the first scientific map of the Atlantic Ocean floor. Her work led to the acceptance of the theories of plate tectonics and continental drift. https://en.wikipedia.org/wiki/Marie_Tharp "tharp", // Ken Thompson - co-creator of UNIX and the C programming language - https://en.wikipedia.org/wiki/Ken_Thompson "thompson", // Linus Torvalds invented Linux and Git. https://en.wikipedia.org/wiki/Linus_Torvalds "torvalds", // Youyou Tu - Chinese pharmaceutical chemist and educator known for discovering artemisinin and dihydroartemisinin, used to treat malaria, which has saved millions of lives. Joint winner of the 2015 Nobel Prize in Physiology or Medicine. https://en.wikipedia.org/wiki/Tu_Youyou "tu", // Alan Turing was a founding father of computer science. https://en.wikipedia.org/wiki/Alan_Turing. "turing", // Varahamihira - Ancient Indian mathematician who discovered trigonometric formulae during 505-587 CE - https://en.wikipedia.org/wiki/Var%C4%81hamihira#Contributions "varahamihira", // Dorothy Vaughan was a NASA mathematician and computer programmer on the SCOUT launch vehicle program that put America's first satellites into space - https://en.wikipedia.org/wiki/Dorothy_Vaughan "vaughan", // Sir Mokshagundam Visvesvaraya - is a notable Indian engineer. He is a recipient of the Indian Republic's highest honour, the Bharat Ratna, in 1955. On his birthday, 15 September is celebrated as Engineer's Day in India in his memory - https://en.wikipedia.org/wiki/Visvesvaraya "visvesvaraya", // Christiane Nüsslein-Volhard - German biologist, won Nobel Prize in Physiology or Medicine in 1995 for research on the genetic control of embryonic development. https://en.wikipedia.org/wiki/Christiane_N%C3%BCsslein-Volhard "volhard", // Cédric Villani - French mathematician, won Fields Medal, Fermat Prize and Poincaré Price for his work in differential geometry and statistical mechanics. https://en.wikipedia.org/wiki/C%C3%A9dric_Villani "villani", // Marlyn Wescoff - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Marlyn_Meltzer "wescoff", // Sylvia B. Wilbur - British computer scientist who helped develop the ARPANET, was one of the first to exchange email in the UK and a leading researcher in computer-supported collaborative work. https://en.wikipedia.org/wiki/Sylvia_Wilbur "wilbur", // Andrew Wiles - Notable British mathematician who proved the enigmatic Fermat's Last Theorem - https://en.wikipedia.org/wiki/Andrew_Wiles "wiles", // Roberta Williams, did pioneering work in graphical adventure games for personal computers, particularly the King's Quest series. https://en.wikipedia.org/wiki/Roberta_Williams "williams", // Malcolm John Williamson - British mathematician and cryptographer employed by the GCHQ. Developed in 1974 what is now known as Diffie-Hellman key exchange (Diffie and Hellman first published the scheme in 1976). https://en.wikipedia.org/wiki/Malcolm_J._Williamson "williamson", // Sophie Wilson designed the first Acorn Micro-Computer and the instruction set for ARM processors. https://en.wikipedia.org/wiki/Sophie_Wilson "wilson", // Jeannette Wing - co-developed the Liskov substitution principle. - https://en.wikipedia.org/wiki/Jeannette_Wing "wing", // Steve Wozniak invented the Apple I and Apple II. https://en.wikipedia.org/wiki/Steve_Wozniak "wozniak", // The Wright brothers, Orville and Wilbur - credited with inventing and building the world's first successful airplane and making the first controlled, powered and sustained heavier-than-air human flight - https://en.wikipedia.org/wiki/Wright_brothers "wright", // Chien-Shiung Wu - Chinese-American experimental physicist who made significant contributions to nuclear physics. https://en.wikipedia.org/wiki/Chien-Shiung_Wu "wu", // Rosalyn Sussman Yalow - Rosalyn Sussman Yalow was an American medical physicist, and a co-winner of the 1977 Nobel Prize in Physiology or Medicine for development of the radioimmunoassay technique. https://en.wikipedia.org/wiki/Rosalyn_Sussman_Yalow "yalow", // Ada Yonath - an Israeli crystallographer, the first woman from the Middle East to win a Nobel prize in the sciences. https://en.wikipedia.org/wiki/Ada_Yonath "yonath", // Nikolay Yegorovich Zhukovsky (Russian: Никола́й Его́рович Жуко́вский, January 17 1847 – March 17, 1921) was a Russian scientist, mathematician and engineer, and a founding father of modern aero- and hydrodynamics. Whereas contemporary scientists scoffed at the idea of human flight, Zhukovsky was the first to undertake the study of airflow. He is often called the Father of Russian Aviation. https://en.wikipedia.org/wiki/Nikolay_Yegorovich_Zhukovsky "zhukovsky" }; /** * Generates cluster tag. * * @return String to use as default cluster tag. */ public static String generateTag() { return new SB() .a(LEFT_PART[new Random().nextInt(LEFT_PART.length)]) .a('_') .a(RIGHT_PART[new Random().nextInt(RIGHT_PART.length)]).toString(); } }
aashish24/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/cluster/ClusterTagGenerator.java
214,040
/* * * This file is part of the iText (R) project. * Copyright (c) 2014-2015 iText Group NV * Authors: Bruno Lowagie, Paulo Soares, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: * http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, * a covered work must retain the producer line in every PDF that is created * or manipulated using iText. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the iText software without * disclosing the source code of your own applications. * These activities include: offering paid services to customers as an ASP, * serving PDFs on the fly in a web application, shipping iText with a closed * source product. * * For more information, please contact iText Software Corp. at this * address: [email protected] * * * This class is based on the C# open source freeware library Clipper: * http://www.angusj.com/delphi/clipper.php * The original classes were distributed under the Boost Software License: * * Freeware for both open source and commercial applications * Copyright 2010-2014 Angus Johnson * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.itextpdf.text.pdf.parser.clipper; public class LongRect { public long left; public long top; public long right; public long bottom; public LongRect() { } public LongRect( long l, long t, long r, long b ) { left = l; top = t; right = r; bottom = b; } public LongRect( LongRect ir ) { left = ir.left; top = ir.top; right = ir.right; bottom = ir.bottom; } }
jieWang0/itextpdf
itext/src/main/java/com/itextpdf/text/pdf/parser/clipper/LongRect.java
214,041
/* NOTICE: This file has been changed by Plutext Pty Ltd for use in docx4j. * The package name has been changed; there may also be other changes. * * This notice is included to meet the condition in clause 4(b) of the License. */ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.docx4j.org.apache.poi.poifs.filesystem; /** * This interface defines methods specific to Document objects * managed by a Filesystem instance. * * @author Marc Johnson (mjohnson at apache dot org) */ public interface DocumentEntry extends Entry { /** * get the zize of the document, in bytes * * @return size in bytes */ public int getSize(); } // end public interface DocumentEntry
plutext/docx4j
docx4j-core/src/main/java/org/docx4j/org/apache/poi/poifs/filesystem/DocumentEntry.java
214,042
package org.apereo.cas.authentication.surrogate; import org.apereo.cas.authentication.principal.Principal; import org.apereo.cas.authentication.principal.Service; import lombok.val; import java.util.Collection; import java.util.Optional; /** * This is {@link SurrogateAuthenticationService}. * It defines operations to note whether one can substitute as another during authentication. * * @author Jonathan Johnson * @author Misagh Moayyed * @since 5.1.0 */ @FunctionalInterface public interface SurrogateAuthenticationService { /** * An authorized account may be tagged as a wildcard, meaning * that the account has special permissions to impersonate anyone. */ String WILDCARD_ACCOUNT = "*"; /** * Default bean name. */ String BEAN_NAME = "surrogateAuthenticationService"; /** * Surrogate username attribute in the authentication payload. */ String AUTHENTICATION_ATTR_SURROGATE_USER = "surrogateUser"; /** * Original credential attribute in the authentication payload. */ String AUTHENTICATION_ATTR_SURROGATE_PRINCIPAL = "surrogatePrincipal"; /** * Indicates that surrogate authn is enabled and activated. */ String AUTHENTICATION_ATTR_SURROGATE_ENABLED = "surrogateEnabled"; /** * Checks whether a principal can authenticate as a surrogate user. * * @param surrogate The username of the surrogate * @param principal the principal * @param service the service * @return true if the given surrogate can authenticate as the user * @throws Throwable the throwable */ default boolean canImpersonate(final String surrogate, final Principal principal, final Optional<? extends Service> service) throws Throwable { return false; } /** * Gets a collection of account names a surrogate can authenticate as. * * @param username The username of the surrogate * @param service the service * @return collection of usernames * @throws Throwable the throwable */ Collection<String> getImpersonationAccounts(String username, Optional<? extends Service> service) throws Throwable; /** * Is wildcarded account authorized?. * * @param surrogate the surrogate * @param principal the principal * @param service the service * @return true /false * @throws Throwable the throwable */ default boolean isWildcardedAccount(final String surrogate, final Principal principal, final Optional<? extends Service> service) throws Throwable{ val accounts = getImpersonationAccounts(principal.getId(), service); return isWildcardedAccount(accounts, service); } /** * Is wildcarded account acepted and found in the given accounts?. * * @param accounts the accounts * @param service the service * @return true /false */ default boolean isWildcardedAccount(final Collection<String> accounts, final Optional<? extends Service> service) { return accounts.size() == 1 && accounts.contains(SurrogateAuthenticationService.WILDCARD_ACCOUNT); } }
leleuj/cas
support/cas-server-support-surrogate-api/src/main/java/org/apereo/cas/authentication/surrogate/SurrogateAuthenticationService.java
214,044
/* NOTICE: This file has been changed by Plutext Pty Ltd for use in docx4j. * The package name has been changed; there may also be other changes. * * This notice is included to meet the condition in clause 4(b) of the License. */ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.docx4j.org.apache.poi.poifs.storage; import java.io.IOException; import java.io.OutputStream; /** * An interface for persisting block storage of POIFS components. * * @author Marc Johnson (mjohnson at apache dot org) */ public interface BlockWritable { /** * Write the storage to an OutputStream * * @param stream the OutputStream to which the stored data should * be written * * @exception IOException on problems writing to the specified * stream */ public void writeBlocks(final OutputStream stream) throws IOException; } // end public interface BlockWritable
plutext/docx4j
docx4j-core/src/main/java/org/docx4j/org/apache/poi/poifs/storage/BlockWritable.java
214,045
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mcxiaoke.next.utils; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.UndeclaredThrowableException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Simple utility class for working with the reflection API and handling * reflection exceptions. * <p/> * <p>Only intended for internal use. * * @author Juergen Hoeller * @author Rob Harrop * @author Rod Johnson * @author Costin Leau * @author Sam Brannen * @author Chris Beams * @since 1.2.2 */ public abstract class ReflectionUtils { /** * Pre-built FieldFilter that matches all non-static, non-final fields. */ public static FieldFilter COPYABLE_FIELDS = new FieldFilter() { @Override public boolean matches(Field field) { return !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())); } }; /** * Pre-built MethodFilter that matches all non-bridge methods. */ public static MethodFilter NON_BRIDGED_METHODS = new MethodFilter() { @Override public boolean matches(Method method) { return !method.isBridge(); } }; /** * Pre-built MethodFilter that matches all non-bridge methods * which are not declared on {@code java.lang.Object}. */ public static MethodFilter USER_DECLARED_METHODS = new MethodFilter() { @Override public boolean matches(Method method) { return (!method.isBridge() && method.getDeclaringClass() != Object.class); } }; /** * Attempt to find a {@link Field field} on the supplied {@link Class} with the * supplied {@code name}. Searches all superclasses up to {@link Object}. * * @param clazz the class to introspect * @param name the name of the field * @return the corresponding Field object, or {@code null} if not found */ public static Field findField(Class<?> clazz, String name) { return findField(clazz, name, null); } /** * Attempt to find a {@link Field field} on the supplied {@link Class} with the * supplied {@code name} and/or {@link Class type}. Searches all superclasses * up to {@link Object}. * * @param clazz the class to introspect * @param name the name of the field (may be {@code null} if type is specified) * @param type the type of the field (may be {@code null} if name is specified) * @return the corresponding Field object, or {@code null} if not found */ public static Field findField(Class<?> clazz, String name, Class<?> type) { AssertUtils.notNull(clazz, "Class must not be null"); AssertUtils.isTrue(name != null || type != null, "Either name or type of the field must be specified"); Class<?> searchType = clazz; while (!Object.class.equals(searchType) && searchType != null) { Field[] fields = searchType.getDeclaredFields(); for (Field field : fields) { if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) { return field; } } searchType = searchType.getSuperclass(); } return null; } /** * Set the field represented by the supplied {@link Field field object} on the * specified {@link Object target object} to the specified {@code value}. * In accordance with {@link Field#set(Object, Object)} semantics, the new value * is automatically unwrapped if the underlying field has a primitive type. * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}. * * @param field the field to set * @param target the target object on which to set the field * @param value the value to set; may be {@code null} */ public static void setField(Field field, Object target, Object value) { try { field.set(target, value); } catch (IllegalAccessException ex) { handleReflectionException(ex); throw new IllegalStateException( "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage()); } } /** * Get the field represented by the supplied {@link Field field object} on the * specified {@link Object target object}. In accordance with {@link Field#get(Object)} * semantics, the returned value is automatically wrapped if the underlying field * has a primitive type. * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}. * * @param field the field to get * @param target the target object from which to get the field * @return the field's current value */ public static Object getField(Field field, Object target) { try { return field.get(target); } catch (IllegalAccessException ex) { handleReflectionException(ex); throw new IllegalStateException( "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage()); } } /** * Attempt to find a {@link Method} on the supplied class with the supplied name * and no parameters. Searches all superclasses up to {@code Object}. * <p>Returns {@code null} if no {@link Method} can be found. * * @param clazz the class to introspect * @param name the name of the method * @return the Method object, or {@code null} if none found */ public static Method findMethod(Class<?> clazz, String name) { return findMethod(clazz, name, new Class<?>[0]); } /** * Attempt to find a {@link Method} on the supplied class with the supplied name * and parameter types. Searches all superclasses up to {@code Object}. * <p>Returns {@code null} if no {@link Method} can be found. * * @param clazz the class to introspect * @param name the name of the method * @param paramTypes the parameter types of the method * (may be {@code null} to indicate any signature) * @return the Method object, or {@code null} if none found */ public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) { AssertUtils.notNull(clazz, "Class must not be null"); AssertUtils.notNull(name, "Method name must not be null"); Class<?> searchType = clazz; while (searchType != null) { Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods()); for (Method method : methods) { if (name.equals(method.getName()) && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) { return method; } } searchType = searchType.getSuperclass(); } return null; } /** * Invoke the specified {@link Method} against the supplied target object with no arguments. * The target object can be {@code null} when invoking a static {@link Method}. * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}. * * @param method the method to invoke * @param target the target object to invoke the method on * @return the invocation result, if any * @see #invokeMethod(Method, Object, Object[]) */ public static Object invokeMethod(Method method, Object target) { return invokeMethod(method, target, new Object[0]); } /** * Invoke the specified {@link Method} against the supplied target object with the * supplied arguments. The target object can be {@code null} when invoking a * static {@link Method}. * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}. * * @param method the method to invoke * @param target the target object to invoke the method on * @param args the invocation arguments (may be {@code null}) * @return the invocation result, if any */ public static Object invokeMethod(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { handleReflectionException(ex); } throw new IllegalStateException("Should never get here"); } /** * Invoke the specified JDBC API {@link Method} against the supplied target * object with no arguments. * * @param method the method to invoke * @param target the target object to invoke the method on * @return the invocation result, if any * @throws SQLException the JDBC API SQLException to rethrow (if any) * @see #invokeJdbcMethod(Method, Object, Object[]) */ public static Object invokeJdbcMethod(Method method, Object target) throws SQLException { return invokeJdbcMethod(method, target, new Object[0]); } /** * Invoke the specified JDBC API {@link Method} against the supplied target * object with the supplied arguments. * * @param method the method to invoke * @param target the target object to invoke the method on * @param args the invocation arguments (may be {@code null}) * @return the invocation result, if any * @throws SQLException the JDBC API SQLException to rethrow (if any) * @see #invokeMethod(Method, Object, Object[]) */ public static Object invokeJdbcMethod(Method method, Object target, Object... args) throws SQLException { try { return method.invoke(target, args); } catch (IllegalAccessException ex) { handleReflectionException(ex); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof SQLException) { throw (SQLException) ex.getTargetException(); } handleInvocationTargetException(ex); } throw new IllegalStateException("Should never get here"); } /** * Handle the given reflection exception. Should only be called if no * checked exception is expected to be thrown by the target method. * <p>Throws the underlying RuntimeException or Error in case of an * InvocationTargetException with such a root cause. Throws an * IllegalStateException with an appropriate message else. * * @param ex the reflection exception to handle */ public static void handleReflectionException(Exception ex) { if (ex instanceof NoSuchMethodException) { throw new IllegalStateException("Method not found: " + ex.getMessage()); } if (ex instanceof IllegalAccessException) { throw new IllegalStateException("Could not access method: " + ex.getMessage()); } if (ex instanceof InvocationTargetException) { handleInvocationTargetException((InvocationTargetException) ex); } if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new UndeclaredThrowableException(ex); } /** * Handle the given invocation target exception. Should only be called if no * checked exception is expected to be thrown by the target method. * <p>Throws the underlying RuntimeException or Error in case of such a root * cause. Throws an IllegalStateException else. * * @param ex the invocation target exception to handle */ public static void handleInvocationTargetException(InvocationTargetException ex) { rethrowRuntimeException(ex.getTargetException()); } /** * Rethrow the given {@link Throwable exception}, which is presumably the * <em>target exception</em> of an {@link InvocationTargetException}. Should * only be called if no checked exception is expected to be thrown by the * target method. * <p>Rethrows the underlying exception cast to an {@link RuntimeException} or * {@link Error} if appropriate; otherwise, throws an * {@link IllegalStateException}. * * @param ex the exception to rethrow * @throws RuntimeException the rethrown exception */ public static void rethrowRuntimeException(Throwable ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } if (ex instanceof Error) { throw (Error) ex; } throw new UndeclaredThrowableException(ex); } /** * Rethrow the given {@link Throwable exception}, which is presumably the * <em>target exception</em> of an {@link InvocationTargetException}. Should * only be called if no checked exception is expected to be thrown by the * target method. * <p>Rethrows the underlying exception cast to an {@link Exception} or * {@link Error} if appropriate; otherwise, throws an * {@link IllegalStateException}. * * @param ex the exception to rethrow * @throws Exception the rethrown exception (in case of a checked exception) */ public static void rethrowException(Throwable ex) throws Exception { if (ex instanceof Exception) { throw (Exception) ex; } if (ex instanceof Error) { throw (Error) ex; } throw new UndeclaredThrowableException(ex); } /** * Determine whether the given method explicitly declares the given * exception or one of its superclasses, which means that an exception of * that type can be propagated as-is within a reflective invocation. * * @param method the declaring method * @param exceptionType the exception to throw * @return {@code true} if the exception can be thrown as-is; * {@code false} if it needs to be wrapped */ public static boolean declaresException(Method method, Class<?> exceptionType) { AssertUtils.notNull(method, "Method must not be null"); Class<?>[] declaredExceptions = method.getExceptionTypes(); for (Class<?> declaredException : declaredExceptions) { if (declaredException.isAssignableFrom(exceptionType)) { return true; } } return false; } /** * Determine whether the given field is a "public static final" constant. * * @param field the field to check */ public static boolean isPublicStaticFinal(Field field) { int modifiers = field.getModifiers(); return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)); } /** * Determine whether the given method is an "equals" method. * * @see Object#equals(Object) */ public static boolean isEqualsMethod(Method method) { if (method == null || !method.getName().equals("equals")) { return false; } Class<?>[] paramTypes = method.getParameterTypes(); return (paramTypes.length == 1 && paramTypes[0] == Object.class); } /** * Determine whether the given method is a "hashCode" method. * * @see Object#hashCode() */ public static boolean isHashCodeMethod(Method method) { return (method != null && method.getName().equals("hashCode") && method.getParameterTypes().length == 0); } /** * Determine whether the given method is a "readString" method. * * @see Object#toString() */ public static boolean isToStringMethod(Method method) { return (method != null && method.getName().equals("readString") && method.getParameterTypes().length == 0); } /** * Determine whether the given method is originally declared by {@link Object}. */ public static boolean isObjectMethod(Method method) { if (method == null) { return false; } try { Object.class.getDeclaredMethod(method.getName(), method.getParameterTypes()); return true; } catch (Exception ex) { return false; } } /** * Make the given field accessible, explicitly setting it accessible if * necessary. The {@code setAccessible(true)} method is only called * when actually necessary, to avoid unnecessary conflicts with a JVM * SecurityManager (if active). * * @param field the field to make accessible * @see Field#setAccessible */ public static void makeAccessible(Field field) { if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) { field.setAccessible(true); } } /** * Make the given method accessible, explicitly setting it accessible if * necessary. The {@code setAccessible(true)} method is only called * when actually necessary, to avoid unnecessary conflicts with a JVM * SecurityManager (if active). * * @param method the method to make accessible * @see Method#setAccessible */ public static void makeAccessible(Method method) { if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) { method.setAccessible(true); } } /** * Make the given constructor accessible, explicitly setting it accessible * if necessary. The {@code setAccessible(true)} method is only called * when actually necessary, to avoid unnecessary conflicts with a JVM * SecurityManager (if active). * * @param ctor the constructor to make accessible * @see Constructor#setAccessible */ public static void makeAccessible(Constructor<?> ctor) { if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) { ctor.setAccessible(true); } } /** * Perform the given callback operation on all matching methods of the given * class and superclasses. * <p>The same named method occurring on subclass and superclass will appear * twice, unless excluded by a {@link MethodFilter}. * * @param clazz class to start looking at * @param mc the callback to invoke for each method * @see #doWithMethods(Class, MethodCallback, MethodFilter) */ public static void doWithMethods(Class<?> clazz, MethodCallback mc) throws IllegalArgumentException { doWithMethods(clazz, mc, null); } /** * Perform the given callback operation on all matching methods of the given * class and superclasses (or given interface and super-interfaces). * <p>The same named method occurring on subclass and superclass will appear * twice, unless excluded by the specified {@link MethodFilter}. * * @param clazz class to start looking at * @param mc the callback to invoke for each method * @param mf the filter that determines the methods to apply the callback to */ public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) throws IllegalArgumentException { // Keep backing up the inheritance hierarchy. Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (mf != null && !mf.matches(method)) { continue; } try { mc.doWith(method); } catch (IllegalAccessException ex) { throw new IllegalStateException("Shouldn't be illegal to access method '" + method.getName() + "': " + ex); } } if (clazz.getSuperclass() != null) { doWithMethods(clazz.getSuperclass(), mc, mf); } else if (clazz.isInterface()) { for (Class<?> superIfc : clazz.getInterfaces()) { doWithMethods(superIfc, mc, mf); } } } /** * Get all declared methods on the leaf class and all superclasses. Leaf * class methods are included first. */ public static Method[] getAllDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { @Override public void doWith(Method method) { methods.add(method); } }); return methods.toArray(new Method[methods.size()]); } /** * Get the unique set of declared methods on the leaf class and all superclasses. Leaf * class methods are included first and while traversing the superclass hierarchy any methods found * with signatures matching a method already included are filtered out. */ public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { @Override public void doWith(Method method) { boolean knownSignature = false; Method methodBeingOverriddenWithCovariantReturnType = null; for (Method existingMethod : methods) { if (method.getName().equals(existingMethod.getName()) && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) { // Is this a covariant return type situation? if (existingMethod.getReturnType() != method.getReturnType() && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) { methodBeingOverriddenWithCovariantReturnType = existingMethod; } else { knownSignature = true; } break; } } if (methodBeingOverriddenWithCovariantReturnType != null) { methods.remove(methodBeingOverriddenWithCovariantReturnType); } if (!knownSignature) { methods.add(method); } } }); return methods.toArray(new Method[methods.size()]); } /** * Invoke the given callback on all fields in the target class, going up the * class hierarchy to get all declared fields. * * @param clazz the target class to analyze * @param fc the callback to invoke for each field */ public static void doWithFields(Class<?> clazz, FieldCallback fc) throws IllegalArgumentException { doWithFields(clazz, fc, null); } /** * Invoke the given callback on all fields in the target class, going up the * class hierarchy to get all declared fields. * * @param clazz the target class to analyze * @param fc the callback to invoke for each field * @param ff the filter that determines the fields to apply the callback to */ public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff) throws IllegalArgumentException { // Keep backing up the inheritance hierarchy. Class<?> targetClass = clazz; do { Field[] fields = targetClass.getDeclaredFields(); for (Field field : fields) { // Skip static and final fields. if (ff != null && !ff.matches(field)) { continue; } try { fc.doWith(field); } catch (IllegalAccessException ex) { throw new IllegalStateException( "Shouldn't be illegal to access field '" + field.getName() + "': " + ex); } } targetClass = targetClass.getSuperclass(); } while (targetClass != null && targetClass != Object.class); } /** * Given the source object and the destination, which must be the same class * or a subclass, copy all fields, including inherited fields. Designed to * work on objects with public no-arg constructors. * * @throws IllegalArgumentException if the arguments are incompatible */ public static void shallowCopyFieldState(final Object src, final Object dest) throws IllegalArgumentException { if (src == null) { throw new IllegalArgumentException("Source for field copy cannot be null"); } if (dest == null) { throw new IllegalArgumentException("Destination for field copy cannot be null"); } if (!src.getClass().isAssignableFrom(dest.getClass())) { throw new IllegalArgumentException("Destination class [" + dest.getClass().getName() + "] must be same or subclass as source class [" + src.getClass().getName() + "]"); } doWithFields(src.getClass(), new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { makeAccessible(field); Object srcValue = field.get(src); field.set(dest, srcValue); } }, COPYABLE_FIELDS); } /** * Action to take on each method. */ public interface MethodCallback { /** * Perform an operation using the given method. * * @param method the method to operate on */ void doWith(Method method) throws IllegalArgumentException, IllegalAccessException; } /** * Callback optionally used to filter methods to be operated on by a method callback. */ public interface MethodFilter { /** * Determine whether the given method matches. * * @param method the method to check */ boolean matches(Method method); } /** * Callback interface invoked on each field in the hierarchy. */ public interface FieldCallback { /** * Perform an operation using the given field. * * @param field the field to operate on */ void doWith(Field field) throws IllegalArgumentException, IllegalAccessException; } /** * Callback optionally used to filter fields to be operated on by a field callback. */ public interface FieldFilter { /** * Determine whether the given field matches. * * @param field the field to check */ boolean matches(Field field); } }
mcxiaoke/Android-Next
core/src/main/java/com/mcxiaoke/next/utils/ReflectionUtils.java
214,046
/* NOTICE: This file has been changed by Plutext Pty Ltd for use in docx4j. * The package name has been changed; there may also be other changes. * * This notice is included to meet the condition in clause 4(b) of the License. */ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.docx4j.org.apache.poi.util; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.text.DecimalFormat; /** * dump data in hexadecimal format; derived from a HexDump utility I * wrote in June 2001. * * @author Marc Johnson * @author Glen Stampoultzis (glens at apache.org) */ public class HexDump { public static final String EOL = System.getProperty("line.separator"); private static final char _hexcodes[] = "0123456789ABCDEF".toCharArray(); private static final int _shifts[] = { 60, 56, 52, 48, 44, 40, 36, 32, 28, 24, 20, 16, 12, 8, 4, 0 }; private HexDump() { // all static methods, so no need for a public constructor } /** * dump an array of bytes to an OutputStream * * @param data the byte array to be dumped * @param offset its offset, whatever that might mean * @param stream the OutputStream to which the data is to be * written * @param index initial index into the byte array * @param length number of characters to output * * @exception IOException is thrown if anything goes wrong writing * the data to stream * @exception ArrayIndexOutOfBoundsException if the index is * outside the data array's bounds * @exception IllegalArgumentException if the output stream is * null */ public static void dump(final byte [] data, final long offset, final OutputStream stream, final int index, final int length) throws IOException, ArrayIndexOutOfBoundsException, IllegalArgumentException { if (data.length == 0) { stream.write( ("No Data" + EOL).getBytes() ); stream.flush(); return; } if ((index < 0) || (index >= data.length)) { throw new ArrayIndexOutOfBoundsException( "illegal index: " + index + " into array of length " + data.length); } if (stream == null) { throw new IllegalArgumentException("cannot write to nullstream"); } long display_offset = offset + index; StringBuffer buffer = new StringBuffer(74); int data_length = Math.min(data.length,index+length); for (int j = index; j < data_length; j += 16) { int chars_read = data_length - j; if (chars_read > 16) { chars_read = 16; } buffer.append( dump(display_offset) ).append(' '); for (int k = 0; k < 16; k++) { if (k < chars_read) { buffer.append(dump(data[ k + j ])); } else { buffer.append(" "); } buffer.append(' '); } for (int k = 0; k < chars_read; k++) { if ((data[ k + j ] >= ' ') && (data[ k + j ] < 127)) { buffer.append(( char ) data[ k + j ]); } else { buffer.append('.'); } } buffer.append(EOL); stream.write(buffer.toString().getBytes()); stream.flush(); buffer.setLength(0); display_offset += chars_read; } } /** * dump an array of bytes to an OutputStream * * @param data the byte array to be dumped * @param offset its offset, whatever that might mean * @param stream the OutputStream to which the data is to be * written * @param index initial index into the byte array * * @exception IOException is thrown if anything goes wrong writing * the data to stream * @exception ArrayIndexOutOfBoundsException if the index is * outside the data array's bounds * @exception IllegalArgumentException if the output stream is * null */ public synchronized static void dump(final byte [] data, final long offset, final OutputStream stream, final int index) throws IOException, ArrayIndexOutOfBoundsException, IllegalArgumentException { dump(data, offset, stream, index, data.length-index); } /** * dump an array of bytes to a String * * @param data the byte array to be dumped * @param offset its offset, whatever that might mean * @param index initial index into the byte array * * @exception ArrayIndexOutOfBoundsException if the index is * outside the data array's bounds * @return output string */ public static String dump(final byte [] data, final long offset, final int index) { StringBuffer buffer; if ((index < 0) || (index >= data.length)) { throw new ArrayIndexOutOfBoundsException( "illegal index: " + index + " into array of length " + data.length); } long display_offset = offset + index; buffer = new StringBuffer(74); for (int j = index; j < data.length; j += 16) { int chars_read = data.length - j; if (chars_read > 16) { chars_read = 16; } buffer.append(dump(display_offset)).append(' '); for (int k = 0; k < 16; k++) { if (k < chars_read) { buffer.append(dump(data[ k + j ])); } else { buffer.append(" "); } buffer.append(' '); } for (int k = 0; k < chars_read; k++) { if ((data[ k + j ] >= ' ') && (data[ k + j ] < 127)) { buffer.append(( char ) data[ k + j ]); } else { buffer.append('.'); } } buffer.append(EOL); display_offset += chars_read; } return buffer.toString(); } private static String dump(final long value) { StringBuffer buf = new StringBuffer(); buf.setLength(0); for (int j = 0; j < 8; j++) { buf.append( _hexcodes[ (( int ) (value >> _shifts[ j + _shifts.length - 8 ])) & 15 ]); } return buf.toString(); } private static String dump(final byte value) { StringBuffer buf = new StringBuffer(); buf.setLength(0); for (int j = 0; j < 2; j++) { buf.append(_hexcodes[ (value >> _shifts[ j + 6 ]) & 15 ]); } return buf.toString(); } /** * Converts the parameter to a hex value. * * @param value The value to convert * @return A String representing the array of bytes */ public static String toHex(final byte[] value) { StringBuffer retVal = new StringBuffer(); retVal.append('['); for(int x = 0; x < value.length; x++) { if (x>0) { retVal.append(", "); } retVal.append(toHex(value[x])); } retVal.append(']'); return retVal.toString(); } /** * Converts the parameter to a hex value. * * @param value The value to convert * @return A String representing the array of shorts */ public static String toHex(final short[] value) { StringBuffer retVal = new StringBuffer(); retVal.append('['); for(int x = 0; x < value.length; x++) { if (x>0) { retVal.append(", "); } retVal.append(toHex(value[x])); } retVal.append(']'); return retVal.toString(); } /** * <p>Converts the parameter to a hex value breaking the results into * lines.</p> * * @param value The value to convert * @param bytesPerLine The maximum number of bytes per line. The next byte * will be written to a new line * @return A String representing the array of bytes */ public static String toHex(final byte[] value, final int bytesPerLine) { final int digits = (int) Math.round(Math.log(value.length) / Math.log(10) + 0.5); final StringBuffer formatString = new StringBuffer(); for (int i = 0; i < digits; i++) formatString.append('0'); formatString.append(": "); final DecimalFormat format = new DecimalFormat(formatString.toString()); StringBuffer retVal = new StringBuffer(); retVal.append(format.format(0)); int i = -1; for(int x = 0; x < value.length; x++) { if (++i == bytesPerLine) { retVal.append('\n'); retVal.append(format.format(x)); i = 0; } else if (x>0) { retVal.append(", "); } retVal.append(toHex(value[x])); } return retVal.toString(); } /** * Converts the parameter to a hex value. * * @param value The value to convert * @return The result right padded with 0 */ public static String toHex(final short value) { return toHex(value, 4); } /** * Converts the parameter to a hex value. * * @param value The value to convert * @return The result right padded with 0 */ public static String toHex(final byte value) { return toHex(value, 2); } /** * Converts the parameter to a hex value. * * @param value The value to convert * @return The result right padded with 0 */ public static String toHex(final int value) { return toHex(value, 8); } /** * Converts the parameter to a hex value. * * @param value The value to convert * @return The result right padded with 0 */ public static String toHex(final long value) { return toHex(value, 16); } private static String toHex(final long value, final int digits) { StringBuffer result = new StringBuffer(digits); for (int j = 0; j < digits; j++) { result.append( _hexcodes[ (int) ((value >> _shifts[ j + (16 - digits) ]) & 15)]); } return result.toString(); } /** * Dumps <code>bytesToDump</code> bytes to an output stream. * * @param in The stream to read from * @param out The output stream * @param start The index to use as the starting position for the left hand side label * @param bytesToDump The number of bytes to output. Use -1 to read until the end of file. */ public static void dump( InputStream in, PrintStream out, int start, int bytesToDump ) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); if (bytesToDump == -1) { int c = in.read(); while (c != -1) { buf.write(c); c = in.read(); } } else { int bytesRemaining = bytesToDump; while (bytesRemaining-- > 0) { int c = in.read(); if (c == -1) { break; } buf.write(c); } } byte[] data = buf.toByteArray(); dump(data, 0, out, start, data.length); } /** * @return char array of uppercase hex chars, zero padded and prefixed with '0x' */ private static char[] toHexChars(long pValue, int nBytes) { int charPos = 2 + nBytes*2; // The return type is char array because most callers will probably append the value to a // StringBuffer, or write it to a Stream / Writer so there is no need to create a String; char[] result = new char[charPos]; long value = pValue; do { result[--charPos] = _hexcodes[(int) (value & 0x0F)]; value >>>= 4; } while (charPos > 1); // Prefix added to avoid ambiguity result[0] = '0'; result[1] = 'x'; return result; } /** * @return char array of 4 (zero padded) uppercase hex chars and prefixed with '0x' */ public static char[] longToHex(long value) { return toHexChars(value, 8); } /** * @return char array of 4 (zero padded) uppercase hex chars and prefixed with '0x' */ public static char[] intToHex(int value) { return toHexChars(value, 4); } /** * @return char array of 2 (zero padded) uppercase hex chars and prefixed with '0x' */ public static char[] shortToHex(int value) { return toHexChars(value, 2); } /** * @return char array of 1 (zero padded) uppercase hex chars and prefixed with '0x' */ public static char[] byteToHex(int value) { return toHexChars(value, 1); } public static void main(String[] args) throws Exception { File file = new File(args[0]); InputStream in = new BufferedInputStream(new FileInputStream(file)); byte[] b = new byte[(int)file.length()]; in.read(b); System.out.println(HexDump.dump(b, 0, 0)); in.close(); } }
plutext/docx4j
docx4j-core/src/main/java/org/docx4j/org/apache/poi/util/HexDump.java
214,047
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package kr.dogfoot.hwplib.org.apache.poi.util; import kr.dogfoot.hwplib.org.apache.poi.util.LittleEndian.BufferUnderrunException; import java.io.IOException; import java.io.InputStream; /** * representation of a short (16-bit) field at a fixed location within * a byte array * * @author Marc Johnson (mjohnson at apache dot org */ public class ShortField implements FixedField { private short _value; private final int _offset; /** * construct the ShortField with its offset into its containing * byte array * * @param offset of the field within its byte array * * @exception ArrayIndexOutOfBoundsException if offset is negative */ public ShortField(final int offset) throws ArrayIndexOutOfBoundsException { if (offset < 0) { throw new ArrayIndexOutOfBoundsException("Illegal offset: " + offset); } _offset = offset; } /** * construct the ShortField with its offset into its containing * byte array and initialize its value * * @param offset of the field within its byte array * @param value the initial value * * @exception ArrayIndexOutOfBoundsException if offset is negative */ public ShortField(final int offset, final short value) throws ArrayIndexOutOfBoundsException { this(offset); set(value); } /** * Construct the ShortField with its offset into its containing * byte array and initialize its value from its byte array * * @param offset of the field within its byte array * @param data the byte array to read the value from * * @exception ArrayIndexOutOfBoundsException if the offset is not * within the range of 0..(data.length - 1) */ public ShortField(final int offset, final byte [] data) throws ArrayIndexOutOfBoundsException { this(offset); readFromBytes(data); } /** * construct the ShortField with its offset into its containing * byte array, initialize its value, and write its value to its * byte array * * @param offset of the field within its byte array * @param value the initial value * @param data the byte array to write the value to * * @exception ArrayIndexOutOfBoundsException if offset is negative */ public ShortField(final int offset, final short value, final byte [] data) throws ArrayIndexOutOfBoundsException { this(offset); set(value, data); } /** * get the ShortField's current value * * @return current value */ public short get() { return _value; } /** * set the ShortField's current value * * @param value to be set */ public void set(final short value) { _value = value; } /** * set the ShortField's current value and write it to a byte array * * @param value to be set * @param data the byte array to write the value to * * @exception ArrayIndexOutOfBoundsException if the offset is out * of range */ public void set(final short value, final byte [] data) throws ArrayIndexOutOfBoundsException { _value = value; writeToBytes(data); } /* ********** START implementation of FixedField ********** */ /** * set the value from its offset into an array of bytes * * @param data the byte array from which the value is to be read * * @exception ArrayIndexOutOfBoundsException if the offset is out * of range */ public void readFromBytes(final byte [] data) throws ArrayIndexOutOfBoundsException { _value = LittleEndian.getShort(data, _offset); } /** * set the value from an InputStream * * @param stream the InputStream from which the value is to be * read * * @exception BufferUnderrunException if there is not enough data * available from the InputStream * @exception IOException if an IOException is thrown from reading * the InputStream */ public void readFromStream(final InputStream stream) throws IOException, BufferUnderrunException { _value = LittleEndian.readShort(stream); } /** * write the value out to an array of bytes at the appropriate * offset * * @param data the array of bytes to which the value is to be * written * * @exception ArrayIndexOutOfBoundsException if the offset is out * of range */ public void writeToBytes(final byte [] data) throws ArrayIndexOutOfBoundsException { LittleEndian.putShort(data, _offset, _value); } /** * return the value as a String * * @return the value as a String */ public String toString() { return String.valueOf(_value); } /* ********** END implementation of FixedField ********** */ } // end public class ShortField
neolord0/hwplib
src/main/java/kr/dogfoot/hwplib/org/apache/poi/util/ShortField.java
214,049
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright 2000, 2010 Oracle and/or its affiliates. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * 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. * *************************************************************************/ import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.beans.XPropertySet; public class OpenQuery { /** * @param args the command line arguments */ public static void main(String[] args) { OpenQuery openQuery1 = new OpenQuery(); try { openQuery1.openQuery(); } catch (java.lang.Exception e){ e.printStackTrace(); } finally { System.exit(0); } } protected void openQuery() throws com.sun.star.uno.Exception, java.lang.Exception { XComponentContext xContext = null; XMultiComponentFactory xMCF = null; try { // get the remote office component context xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); System.out.println("Connected to a running office ..."); xMCF = xContext.getServiceManager(); } catch( Exception e) { System.err.println("ERROR: can't get a component context from a running office ..."); e.printStackTrace(); System.exit(1); } // first we create our RowSet object and get its XRowSet interface Object rowSet = xMCF.createInstanceWithContext( "com.sun.star.sdb.RowSet", xContext); com.sun.star.sdbc.XRowSet xRowSet = UnoRuntime.queryInterface(com.sun.star.sdbc.XRowSet.class, rowSet); // set the properties needed to connect to a database XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class, xRowSet); // the DataSourceName can be a data source registered with [PRODUCTNAME], among other possibilities xProp.setPropertyValue("DataSourceName","Bibliography"); // the CommandType must be TABLE, QUERY or COMMAND, here we use COMMAND xProp.setPropertyValue("CommandType",Integer.valueOf(com.sun.star.sdb.CommandType.COMMAND)); // the Command could be a table or query name or a SQL command, depending on the CommandType xProp.setPropertyValue("Command","SELECT IDENTIFIER, AUTHOR FROM biblio ORDER BY IDENTIFIER"); // if your database requires logon, you can use the properties User and Password // xProp.setPropertyValue("User", "JohnDoe"); // xProp.setPropertyValue("Password", "mysecret"); xRowSet.execute(); // prepare the XRow and XColumnLocate interface for column access // XRow gets column values com.sun.star.sdbc.XRow xRow = UnoRuntime.queryInterface( com.sun.star.sdbc.XRow.class, xRowSet); // XColumnLocate finds columns by name com.sun.star.sdbc.XColumnLocate xLoc = UnoRuntime.queryInterface( com.sun.star.sdbc.XColumnLocate.class, xRowSet); // print output header System.out.println("Identifier\tAuthor"); System.out.println("----------\t------"); // output result rows while ( xRowSet.next() ) { String ident = xRow.getString(xLoc.findColumn("IDENTIFIER")); String author = xRow.getString(xLoc.findColumn("AUTHOR")); System.out.println(ident + "\t\t" + author); } // XResultSetUpdate for insertRow handling com.sun.star.sdbc.XResultSetUpdate xResultSetUpdate = UnoRuntime.queryInterface( com.sun.star.sdbc.XResultSetUpdate.class, xRowSet); // XRowUpdate for row updates com.sun.star.sdbc.XRowUpdate xRowUpdate = UnoRuntime.queryInterface( com.sun.star.sdbc.XRowUpdate.class, xRowSet); // move to insertRow buffer xResultSetUpdate.moveToInsertRow(); // edit insertRow buffer xRowUpdate.updateString(xLoc.findColumn("IDENTIFIER"), "GOF95"); xRowUpdate.updateString(xLoc.findColumn("AUTHOR"), "Gamma, Helm, Johnson, Vlissides"); // write buffer to database xResultSetUpdate.insertRow(); // throw away the row set com.sun.star.lang.XComponent xComp = UnoRuntime.queryInterface( com.sun.star.lang.XComponent.class, xRowSet); xComp.dispose(); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
LibreOffice/core
odk/examples/DevelopersGuide/Database/OpenQuery.java
214,050
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.support; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.util.ObjectUtils; /** * Programmatic means of constructing * {@link org.springframework.beans.factory.config.BeanDefinition BeanDefinitions} * using the builder pattern. Intended primarily for use when implementing Spring 2.0 * {@link org.springframework.beans.factory.xml.NamespaceHandler NamespaceHandlers}. * * @author Rod Johnson * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 */ public class BeanDefinitionBuilder { /** * Create a new {@code BeanDefinitionBuilder} used to construct a {@link GenericBeanDefinition}. */ public static BeanDefinitionBuilder genericBeanDefinition() { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new GenericBeanDefinition(); return builder; } /** * Create a new {@code BeanDefinitionBuilder} used to construct a {@link GenericBeanDefinition}. * @param beanClass the {@code Class} of the bean that the definition is being created for */ public static BeanDefinitionBuilder genericBeanDefinition(Class<?> beanClass) { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new GenericBeanDefinition(); builder.beanDefinition.setBeanClass(beanClass); return builder; } /** * Create a new {@code BeanDefinitionBuilder} used to construct a {@link GenericBeanDefinition}. * @param beanClassName the class name for the bean that the definition is being created for */ public static BeanDefinitionBuilder genericBeanDefinition(String beanClassName) { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new GenericBeanDefinition(); builder.beanDefinition.setBeanClassName(beanClassName); return builder; } /** * Create a new {@code BeanDefinitionBuilder} used to construct a {@link RootBeanDefinition}. * @param beanClass the {@code Class} of the bean that the definition is being created for */ public static BeanDefinitionBuilder rootBeanDefinition(Class<?> beanClass) { return rootBeanDefinition(beanClass, null); } /** * Create a new {@code BeanDefinitionBuilder} used to construct a {@link RootBeanDefinition}. * @param beanClass the {@code Class} of the bean that the definition is being created for * @param factoryMethodName the name of the method to use to construct the bean instance */ public static BeanDefinitionBuilder rootBeanDefinition(Class<?> beanClass, String factoryMethodName) { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new RootBeanDefinition(); builder.beanDefinition.setBeanClass(beanClass); builder.beanDefinition.setFactoryMethodName(factoryMethodName); return builder; } /** * Create a new {@code BeanDefinitionBuilder} used to construct a {@link RootBeanDefinition}. * @param beanClassName the class name for the bean that the definition is being created for */ public static BeanDefinitionBuilder rootBeanDefinition(String beanClassName) { return rootBeanDefinition(beanClassName, null); } /** * Create a new {@code BeanDefinitionBuilder} used to construct a {@link RootBeanDefinition}. * @param beanClassName the class name for the bean that the definition is being created for * @param factoryMethodName the name of the method to use to construct the bean instance */ public static BeanDefinitionBuilder rootBeanDefinition(String beanClassName, String factoryMethodName) { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new RootBeanDefinition(); builder.beanDefinition.setBeanClassName(beanClassName); builder.beanDefinition.setFactoryMethodName(factoryMethodName); return builder; } /** * Create a new {@code BeanDefinitionBuilder} used to construct a {@link ChildBeanDefinition}. * @param parentName the name of the parent bean */ public static BeanDefinitionBuilder childBeanDefinition(String parentName) { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new ChildBeanDefinition(parentName); return builder; } /** * The {@code BeanDefinition} instance we are creating. */ private AbstractBeanDefinition beanDefinition; /** * Our current position with respect to constructor args. */ private int constructorArgIndex; /** * Enforce the use of factory methods. */ private BeanDefinitionBuilder() { } /** * Return the current BeanDefinition object in its raw (unvalidated) form. * @see #getBeanDefinition() */ public AbstractBeanDefinition getRawBeanDefinition() { return this.beanDefinition; } /** * Validate and return the created BeanDefinition object. */ public AbstractBeanDefinition getBeanDefinition() { this.beanDefinition.validate(); return this.beanDefinition; } /** * Set the name of the parent definition of this bean definition. */ public BeanDefinitionBuilder setParentName(String parentName) { this.beanDefinition.setParentName(parentName); return this; } /** * Set the name of the factory method to use for this definition. */ public BeanDefinitionBuilder setFactoryMethod(String factoryMethod) { this.beanDefinition.setFactoryMethodName(factoryMethod); return this; } /** * Add an indexed constructor arg value. The current index is tracked internally * and all additions are at the present point. * @deprecated since Spring 2.5, in favor of {@link #addConstructorArgValue} */ @Deprecated public BeanDefinitionBuilder addConstructorArg(Object value) { return addConstructorArgValue(value); } /** * Add an indexed constructor arg value. The current index is tracked internally * and all additions are at the present point. */ public BeanDefinitionBuilder addConstructorArgValue(Object value) { this.beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue( this.constructorArgIndex++, value); return this; } /** * Add a reference to a named bean as a constructor arg. * @see #addConstructorArgValue(Object) */ public BeanDefinitionBuilder addConstructorArgReference(String beanName) { this.beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue( this.constructorArgIndex++, new RuntimeBeanReference(beanName)); return this; } /** * Add the supplied property value under the given name. */ public BeanDefinitionBuilder addPropertyValue(String name, Object value) { this.beanDefinition.getPropertyValues().add(name, value); return this; } /** * Add a reference to the specified bean name under the property specified. * @param name the name of the property to add the reference to * @param beanName the name of the bean being referenced */ public BeanDefinitionBuilder addPropertyReference(String name, String beanName) { this.beanDefinition.getPropertyValues().add(name, new RuntimeBeanReference(beanName)); return this; } /** * Set the init method for this definition. */ public BeanDefinitionBuilder setInitMethodName(String methodName) { this.beanDefinition.setInitMethodName(methodName); return this; } /** * Set the destroy method for this definition. */ public BeanDefinitionBuilder setDestroyMethodName(String methodName) { this.beanDefinition.setDestroyMethodName(methodName); return this; } /** * Set the scope of this definition. * @see org.springframework.beans.factory.config.BeanDefinition#SCOPE_SINGLETON * @see org.springframework.beans.factory.config.BeanDefinition#SCOPE_PROTOTYPE */ public BeanDefinitionBuilder setScope(String scope) { this.beanDefinition.setScope(scope); return this; } /** * Set whether or not this definition is abstract. */ public BeanDefinitionBuilder setAbstract(boolean flag) { this.beanDefinition.setAbstract(flag); return this; } /** * Set whether beans for this definition should be lazily initialized or not. */ public BeanDefinitionBuilder setLazyInit(boolean lazy) { this.beanDefinition.setLazyInit(lazy); return this; } /** * Set the autowire mode for this definition. */ public BeanDefinitionBuilder setAutowireMode(int autowireMode) { beanDefinition.setAutowireMode(autowireMode); return this; } /** * Set the depency check mode for this definition. */ public BeanDefinitionBuilder setDependencyCheck(int dependencyCheck) { beanDefinition.setDependencyCheck(dependencyCheck); return this; } /** * Append the specified bean name to the list of beans that this definition * depends on. */ public BeanDefinitionBuilder addDependsOn(String beanName) { if (this.beanDefinition.getDependsOn() == null) { this.beanDefinition.setDependsOn(new String[] {beanName}); } else { String[] added = ObjectUtils.addObjectToArray(this.beanDefinition.getDependsOn(), beanName); this.beanDefinition.setDependsOn(added); } return this; } /** * Set the role of this definition. */ public BeanDefinitionBuilder setRole(int role) { this.beanDefinition.setRole(role); return this; } }
jinchihe/blog_demos
springbeans_modify/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java
214,051
/* NOTICE: This file has been changed by Plutext Pty Ltd for use in docx4j. * The package name has been changed; there may also be other changes. * * This notice is included to meet the condition in clause 4(b) of the License. */ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.docx4j.org.apache.poi.poifs.filesystem; /** * Class POIFSWriterEvent * * @author Marc Johnson (mjohnson at apache dot org) * @version %I%, %G% */ public class POIFSWriterEvent { private DocumentOutputStream stream; private POIFSDocumentPath path; private String documentName; private int limit; /** * package scoped constructor * * @param stream the DocumentOutputStream, freshly opened * @param path the path of the document * @param documentName the name of the document * @param limit the limit, in bytes, that can be written to the * stream */ POIFSWriterEvent(final DocumentOutputStream stream, final POIFSDocumentPath path, final String documentName, final int limit) { this.stream = stream; this.path = path; this.documentName = documentName; this.limit = limit; } /** * @return the DocumentOutputStream, freshly opened */ public DocumentOutputStream getStream() { return stream; } /** * @return the document's path */ public POIFSDocumentPath getPath() { return path; } /** * @return the document's name */ public String getName() { return documentName; } /** * @return the limit on writing, in bytes */ public int getLimit() { return limit; } } // end public class POIFSWriterEvent
plutext/docx4j
docx4j-core/src/main/java/org/docx4j/org/apache/poi/poifs/filesystem/POIFSWriterEvent.java
214,052
404: Not Found
liu-657667/nacos
common/src/main/java/com/alibaba/nacos/common/packagescan/util/AbstractObjectUtils.java
214,053
/* ### * IP: GHIDRA * * 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 ghidra.graph.algo; import java.util.*; import ghidra.graph.GDirectedGraph; import ghidra.graph.GEdge; import ghidra.graph.algo.GraphAlgorithmStatusListener.STATUS; import ghidra.util.datastruct.Accumulator; import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskMonitor; /** * Finds all paths between two vertices for a given graph. * * <P><B><U>Warning:</U></B> This is a recursive algorithm. As such, it is limited in how deep * it can recurse. Any path that exceeds the {@link #JAVA_STACK_DEPTH_LIMIT} will not be found. * * <P>Note: this algorithm is based entirely on the {@link JohnsonCircuitsAlgorithm}. * * @param <V> the vertex type * @param <E> the edge type */ public class RecursiveFindPathsAlgorithm<V, E extends GEdge<V>> implements FindPathsAlgorithm<V, E> { public static final int JAVA_STACK_DEPTH_LIMIT = 2700; private GDirectedGraph<V, E> g; private V startVertex; private V endVertex; private Stack<V> stack = new Stack<>(); private Set<V> blockedSet = new HashSet<>(); private Map<V, Set<V>> blockedBackEdgesMap = new HashMap<>(); private Accumulator<List<V>> accumulator; private TaskMonitor monitor; private GraphAlgorithmStatusListener<V> listener = new GraphAlgorithmStatusListener<>(); @Override public void setStatusListener(GraphAlgorithmStatusListener<V> listener) { this.listener = listener; } @SuppressWarnings("hiding") // squash warning on names of variables @Override public void findPaths(GDirectedGraph<V, E> g, V start, V end, Accumulator<List<V>> accumulator, TaskMonitor monitor) throws CancelledException { this.g = g; this.startVertex = start; this.endVertex = end; this.accumulator = accumulator; this.monitor = monitor; explore(startVertex, 0); listener.finished(); } private boolean explore(V v, int depth) throws CancelledException { // TODO // Sigh. We are greatly limited in the size of paths we can processes due to the // recursive nature of this algorithm. This should be changed to be non-recursive. if (depth > JAVA_STACK_DEPTH_LIMIT) { return false; } boolean foundPath = false; blockedSet.add(v); stack.push(v); setStatus(v, STATUS.EXPLORING); Collection<E> outEdges = getOutEdges(v); for (E e : outEdges) { monitor.checkCancelled(); V u = e.getEnd(); if (u.equals(endVertex)) { outputCircuit(); foundPath = true; monitor.incrementProgress(1); } else if (!blockedSet.contains(u)) { foundPath |= explore(u, depth + 1); monitor.incrementProgress(1); } } if (foundPath) { unblock(v); } else { for (E e : outEdges) { monitor.checkCancelled(); V u = e.getEnd(); blockBackEdge(u, v); } } stack.pop(); setStatus(v, STATUS.WAITING); return foundPath; } private Collection<E> getOutEdges(V v) { Collection<E> outEdges = g.getOutEdges(v); if (outEdges == null) { return Collections.emptyList(); } return outEdges; } private void unblock(V v) { blockedSet.remove(v); setStatus(v, STATUS.WAITING); Set<V> set = blockedBackEdgesMap.get(v); if (set == null) { return; } for (V u : set) { if (blockedSet.contains(u)) { unblock(u); } } set.clear(); } private void blockBackEdge(V u, V v) { Set<V> set = blockedBackEdgesMap.get(u); if (set == null) { set = new HashSet<>(); blockedBackEdgesMap.put(u, set); } set.add(v); setStatus(v, STATUS.BLOCKED); } private void outputCircuit() throws CancelledException { List<V> path = new LinkedList<>(stack); path.add(endVertex); setStatus(path, STATUS.IN_PATH); accumulator.add(path); monitor.checkCancelled(); // pause for listener setStatus(endVertex, STATUS.WAITING); } private void setStatus(List<V> path, STATUS s) { for (V v : path) { listener.statusChanged(v, s); } } private void setStatus(V v, STATUS s) { if (blockedSet.contains(v) && s == STATUS.WAITING) { listener.statusChanged(v, STATUS.BLOCKED); } else { listener.statusChanged(v, s); } } }
NationalSecurityAgency/ghidra
Ghidra/Framework/Graph/src/main/java/ghidra/graph/algo/RecursiveFindPathsAlgorithm.java
214,054
/* NOTICE: This file has been changed by Plutext Pty Ltd for use in docx4j. * The package name has been changed; there may also be other changes. * * This notice is included to meet the condition in clause 4(b) of the License. */ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.docx4j.org.apache.poi.poifs.property; /** * This interface defines methods for finding and setting sibling * Property instances * * @author Marc Johnson (mjohnson at apache dot org) */ public interface Child { /** * Get the next Child, if any * * @return the next Child; may return null */ public Child getNextChild(); /** * Get the previous Child, if any * * @return the previous Child; may return null */ public Child getPreviousChild(); /** * Set the next Child * * @param child the new 'next' child; may be null, which has the * effect of saying there is no 'next' child */ public void setNextChild(final Child child); /** * Set the previous Child * * @param child the new 'previous' child; may be null, which has * the effect of saying there is no 'previous' child */ public void setPreviousChild(final Child child); } // end public interface Child
plutext/docx4j
docx4j-core/src/main/java/org/docx4j/org/apache/poi/poifs/property/Child.java
214,055
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hotswap.agent.util.spring.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.UndeclaredThrowableException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.hotswap.agent.util.spring.collections.ConcurrentReferenceHashMap; /** * Simple utility class for working with the reflection API and handling * reflection exceptions. * * <p> * Only intended for internal use. * * @author Juergen Hoeller * @author Rob Harrop * @author Rod Johnson * @author Costin Leau * @author Sam Brannen * @author Chris Beams * @since 1.2.2 */ public abstract class ReflectionUtils { /** * Naming prefix for CGLIB-renamed methods. * * @see #isCglibRenamedMethod */ private static final String CGLIB_RENAMED_METHOD_PREFIX = "CGLIB$"; /** * Cache for {@link Class#getDeclaredMethods()} plus equivalent default * methods from Java 8 based interfaces, allowing for fast iteration. */ private static final Map<Class<?>, Method[]> declaredMethodsCache = new ConcurrentReferenceHashMap<Class<?>, Method[]>(256); /** * Cache for {@link Class#getDeclaredFields()}, allowing for fast iteration. */ private static final Map<Class<?>, Field[]> declaredFieldsCache = new ConcurrentReferenceHashMap<Class<?>, Field[]>(256); /** * Attempt to find a {@link Field field} on the supplied {@link Class} with * the supplied {@code name}. Searches all superclasses up to {@link Object} * . * * @param clazz * the class to introspect * @param name * the name of the field * @return the corresponding Field object, or {@code null} if not found */ public static Field findField(Class<?> clazz, String name) { return findField(clazz, name, null); } /** * Attempt to find a {@link Field field} on the supplied {@link Class} with * the supplied {@code name} and/or {@link Class type}. Searches all * superclasses up to {@link Object}. * * @param clazz * the class to introspect * @param name * the name of the field (may be {@code null} if type is * specified) * @param type * the type of the field (may be {@code null} if name is * specified) * @return the corresponding Field object, or {@code null} if not found */ public static Field findField(Class<?> clazz, String name, Class<?> type) { Assert.notNull(clazz, "Class must not be null"); Assert.isTrue(name != null || type != null, "Either name or type of the field must be specified"); Class<?> searchType = clazz; while (Object.class != searchType && searchType != null) { Field[] fields = getDeclaredFields(searchType); for (Field field : fields) { if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) { return field; } } searchType = searchType.getSuperclass(); } return null; } /** * Set the field represented by the supplied {@link Field field object} on * the specified {@link Object target object} to the specified {@code value} * . In accordance with {@link Field#set(Object, Object)} semantics, the new * value is automatically unwrapped if the underlying field has a primitive * type. * <p> * Thrown exceptions are handled via a call to * {@link #handleReflectionException(Exception)}. * * @param field * the field to set * @param target * the target object on which to set the field * @param value * the value to set; may be {@code null} */ public static void setField(Field field, Object target, Object value) { try { field.set(target, value); } catch (IllegalAccessException ex) { handleReflectionException(ex); throw new IllegalStateException("Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage()); } } /** * Get the field represented by the supplied {@link Field field object} on * the specified {@link Object target object}. In accordance with * {@link Field#get(Object)} semantics, the returned value is automatically * wrapped if the underlying field has a primitive type. * <p> * Thrown exceptions are handled via a call to * {@link #handleReflectionException(Exception)}. * * @param field * the field to get * @param target * the target object from which to get the field * @return the field's current value */ @SuppressWarnings("unchecked") public static <T> T getField(Field field, Object target) { try { return (T) field.get(target); } catch (IllegalAccessException ex) { handleReflectionException(ex); throw new IllegalStateException("Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage()); } } /** * Attempt to find a {@link Method} on the supplied class with the supplied * name and no parameters. Searches all superclasses up to {@code Object}. * <p> * Returns {@code null} if no {@link Method} can be found. * * @param clazz * the class to introspect * @param name * the name of the method * @return the Method object, or {@code null} if none found */ public static Method findMethod(Class<?> clazz, String name) { return findMethod(clazz, name, new Class<?>[0]); } /** * Attempt to find a {@link Method} on the supplied class with the supplied * name and parameter types. Searches all superclasses up to {@code Object}. * <p> * Returns {@code null} if no {@link Method} can be found. * * @param clazz * the class to introspect * @param name * the name of the method * @param paramTypes * the parameter types of the method (may be {@code null} to * indicate any signature) * @return the Method object, or {@code null} if none found */ public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(name, "Method name must not be null"); Class<?> searchType = clazz; while (searchType != null) { Method[] methods = (searchType.isInterface() ? searchType.getMethods() : getDeclaredMethods(searchType)); for (Method method : methods) { if (name.equals(method.getName()) && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) { return method; } } searchType = searchType.getSuperclass(); } return null; } /** * Invoke the specified {@link Method} against the supplied target object * with no arguments. The target object can be {@code null} when invoking a * static {@link Method}. * <p> * Thrown exceptions are handled via a call to * {@link #handleReflectionException}. * * @param method * the method to invoke * @param target * the target object to invoke the method on * @return the invocation result, if any * @see #invokeMethod(java.lang.reflect.Method, Object, Object[]) */ public static <T> T invokeMethod(Method method, Object target) { return invokeMethod(method, target, new Object[0]); } /** * Invoke the specified {@link Method} against the supplied target object * with the supplied arguments. The target object can be {@code null} when * invoking a static {@link Method}. * <p> * Thrown exceptions are handled via a call to * {@link #handleReflectionException}. * * @param method * the method to invoke * @param target * the target object to invoke the method on * @param args * the invocation arguments (may be {@code null}) * @return the invocation result, if any */ @SuppressWarnings("unchecked") public static <T> T invokeMethod(Method method, Object target, Object... args) { try { return (T) method.invoke(target, args); } catch (Exception ex) { handleReflectionException(ex); } throw new IllegalStateException("Should never get here"); } /** * Invoke the specified JDBC API {@link Method} against the supplied target * object with no arguments. * * @param method * the method to invoke * @param target * the target object to invoke the method on * @return the invocation result, if any * @throws SQLException * the JDBC API SQLException to rethrow (if any) * @see #invokeJdbcMethod(java.lang.reflect.Method, Object, Object[]) */ public static <T> T invokeJdbcMethod(Method method, Object target) throws SQLException { return invokeJdbcMethod(method, target, new Object[0]); } /** * Invoke the specified JDBC API {@link Method} against the supplied target * object with the supplied arguments. * * @param method * the method to invoke * @param target * the target object to invoke the method on * @param args * the invocation arguments (may be {@code null}) * @return the invocation result, if any * @throws SQLException * the JDBC API SQLException to rethrow (if any) * @see #invokeMethod(java.lang.reflect.Method, Object, Object[]) */ @SuppressWarnings("unchecked") public static <T> T invokeJdbcMethod(Method method, Object target, Object... args) throws SQLException { try { return (T) method.invoke(target, args); } catch (IllegalAccessException ex) { handleReflectionException(ex); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof SQLException) { throw (SQLException) ex.getTargetException(); } handleInvocationTargetException(ex); } throw new IllegalStateException("Should never get here"); } /** * Handle the given reflection exception. Should only be called if no * checked exception is expected to be thrown by the target method. * <p> * Throws the underlying RuntimeException or Error in case of an * InvocationTargetException with such a root cause. Throws an * IllegalStateException with an appropriate message else. * * @param ex * the reflection exception to handle */ public static void handleReflectionException(Exception ex) { if (ex instanceof NoSuchMethodException) { throw new IllegalStateException("Method not found: " + ex.getMessage()); } if (ex instanceof IllegalAccessException) { throw new IllegalStateException("Could not access method: " + ex.getMessage()); } if (ex instanceof InvocationTargetException) { handleInvocationTargetException((InvocationTargetException) ex); } if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new UndeclaredThrowableException(ex); } /** * Handle the given invocation target exception. Should only be called if no * checked exception is expected to be thrown by the target method. * <p> * Throws the underlying RuntimeException or Error in case of such a root * cause. Throws an IllegalStateException else. * * @param ex * the invocation target exception to handle */ public static void handleInvocationTargetException(InvocationTargetException ex) { rethrowRuntimeException(ex.getTargetException()); } /** * Rethrow the given {@link Throwable exception}, which is presumably the * <em>target exception</em> of an {@link InvocationTargetException}. Should * only be called if no checked exception is expected to be thrown by the * target method. * <p> * Rethrows the underlying exception cast to an {@link RuntimeException} or * {@link Error} if appropriate; otherwise, throws an * {@link IllegalStateException}. * * @param ex * the exception to rethrow * @throws RuntimeException * the rethrown exception */ public static void rethrowRuntimeException(Throwable ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } if (ex instanceof Error) { throw (Error) ex; } throw new UndeclaredThrowableException(ex); } /** * Rethrow the given {@link Throwable exception}, which is presumably the * <em>target exception</em> of an {@link InvocationTargetException}. Should * only be called if no checked exception is expected to be thrown by the * target method. * <p> * Rethrows the underlying exception cast to an {@link Exception} or * {@link Error} if appropriate; otherwise, throws an * {@link IllegalStateException}. * * @param ex * the exception to rethrow * @throws Exception * the rethrown exception (in case of a checked exception) */ public static void rethrowException(Throwable ex) throws Exception { if (ex instanceof Exception) { throw (Exception) ex; } if (ex instanceof Error) { throw (Error) ex; } throw new UndeclaredThrowableException(ex); } /** * Determine whether the given method explicitly declares the given * exception or one of its superclasses, which means that an exception of * that type can be propagated as-is within a reflective invocation. * * @param method * the declaring method * @param exceptionType * the exception to throw * @return {@code true} if the exception can be thrown as-is; {@code false} * if it needs to be wrapped */ public static boolean declaresException(Method method, Class<?> exceptionType) { Assert.notNull(method, "Method must not be null"); Class<?>[] declaredExceptions = method.getExceptionTypes(); for (Class<?> declaredException : declaredExceptions) { if (declaredException.isAssignableFrom(exceptionType)) { return true; } } return false; } /** * Determine whether the given field is a "public static final" constant. * * @param field * the field to check */ public static boolean isPublicStaticFinal(Field field) { int modifiers = field.getModifiers(); return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)); } /** * Determine whether the given method is an "equals" method. * * @see java.lang.Object#equals(Object) */ public static boolean isEqualsMethod(Method method) { if (method == null || !method.getName().equals("equals")) { return false; } Class<?>[] paramTypes = method.getParameterTypes(); return (paramTypes.length == 1 && paramTypes[0] == Object.class); } /** * Determine whether the given method is a "hashCode" method. * * @see java.lang.Object#hashCode() */ public static boolean isHashCodeMethod(Method method) { return (method != null && method.getName().equals("hashCode") && method.getParameterTypes().length == 0); } /** * Determine whether the given method is a "toString" method. * * @see java.lang.Object#toString() */ public static boolean isToStringMethod(Method method) { return (method != null && method.getName().equals("toString") && method.getParameterTypes().length == 0); } /** * Determine whether the given method is originally declared by * {@link java.lang.Object}. */ public static boolean isObjectMethod(Method method) { if (method == null) { return false; } try { Object.class.getDeclaredMethod(method.getName(), method.getParameterTypes()); return true; } catch (Exception ex) { return false; } } /** * Determine whether the given method is a CGLIB 'renamed' method, following * the pattern "CGLIB$methodName$0". * * @param renamedMethod * the method to check * @see org.springframework.cglib.proxy.Enhancer#rename */ public static boolean isCglibRenamedMethod(Method renamedMethod) { String name = renamedMethod.getName(); if (name.startsWith(CGLIB_RENAMED_METHOD_PREFIX)) { int i = name.length() - 1; while (i >= 0 && Character.isDigit(name.charAt(i))) { i--; } return ((i > CGLIB_RENAMED_METHOD_PREFIX.length()) && (i < name.length() - 1) && name.charAt(i) == '$'); } return false; } /** * Make the given field accessible, explicitly setting it accessible if * necessary. The {@code setAccessible(true)} method is only called when * actually necessary, to avoid unnecessary conflicts with a JVM * SecurityManager (if active). * * @param field * the field to make accessible * @see java.lang.reflect.Field#setAccessible */ public static void makeAccessible(Field field) { if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) { field.setAccessible(true); } } /** * Make the given method accessible, explicitly setting it accessible if * necessary. The {@code setAccessible(true)} method is only called when * actually necessary, to avoid unnecessary conflicts with a JVM * SecurityManager (if active). * * @param method * the method to make accessible * @see java.lang.reflect.Method#setAccessible */ public static void makeAccessible(Method method) { if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) { method.setAccessible(true); } } /** * Make the given constructor accessible, explicitly setting it accessible * if necessary. The {@code setAccessible(true)} method is only called when * actually necessary, to avoid unnecessary conflicts with a JVM * SecurityManager (if active). * * @param ctor * the constructor to make accessible * @see java.lang.reflect.Constructor#setAccessible */ public static void makeAccessible(Constructor<?> ctor) { if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) { ctor.setAccessible(true); } } /** * Perform the given callback operation on all matching methods of the given * class, as locally declared or equivalent thereof (such as default methods * on Java 8 based interfaces that the given class implements). * * @param clazz * the class to introspect * @param mc * the callback to invoke for each method * @since 4.2 * @see #doWithMethods */ public static void doWithLocalMethods(Class<?> clazz, MethodCallback mc) { Method[] methods = getDeclaredMethods(clazz); for (Method method : methods) { try { mc.doWith(method); } catch (IllegalAccessException ex) { throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + ex); } } } /** * Perform the given callback operation on all matching methods of the given * class and superclasses. * <p> * The same named method occurring on subclass and superclass will appear * twice, unless excluded by a {@link MethodFilter}. * * @param clazz * the class to introspect * @param mc * the callback to invoke for each method * @see #doWithMethods(Class, MethodCallback, MethodFilter) */ public static void doWithMethods(Class<?> clazz, MethodCallback mc) { doWithMethods(clazz, mc, null); } /** * Perform the given callback operation on all matching methods of the given * class and superclasses (or given interface and super-interfaces). * <p> * The same named method occurring on subclass and superclass will appear * twice, unless excluded by the specified {@link MethodFilter}. * * @param clazz * the class to introspect * @param mc * the callback to invoke for each method * @param mf * the filter that determines the methods to apply the callback * to */ public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) { // Keep backing up the inheritance hierarchy. Method[] methods = getDeclaredMethods(clazz); for (Method method : methods) { if (mf != null && !mf.matches(method)) { continue; } try { mc.doWith(method); } catch (IllegalAccessException ex) { throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + ex); } } if (clazz.getSuperclass() != null) { doWithMethods(clazz.getSuperclass(), mc, mf); } else if (clazz.isInterface()) { for (Class<?> superIfc : clazz.getInterfaces()) { doWithMethods(superIfc, mc, mf); } } } /** * Get all declared methods on the leaf class and all superclasses. Leaf * class methods are included first. * * @param leafClass * the class to introspect */ public static Method[] getAllDeclaredMethods(Class<?> leafClass) { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { @Override public void doWith(Method method) { methods.add(method); } }); return methods.toArray(new Method[methods.size()]); } /** * Get the unique set of declared methods on the leaf class and all * superclasses. Leaf class methods are included first and while traversing * the superclass hierarchy any methods found with signatures matching a * method already included are filtered out. * * @param leafClass * the class to introspect */ public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { @Override public void doWith(Method method) { boolean knownSignature = false; Method methodBeingOverriddenWithCovariantReturnType = null; for (Method existingMethod : methods) { if (method.getName().equals(existingMethod.getName()) && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) { // Is this a covariant return type situation? if (existingMethod.getReturnType() != method.getReturnType() && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) { methodBeingOverriddenWithCovariantReturnType = existingMethod; } else { knownSignature = true; } break; } } if (methodBeingOverriddenWithCovariantReturnType != null) { methods.remove(methodBeingOverriddenWithCovariantReturnType); } if (!knownSignature && !isCglibRenamedMethod(method)) { methods.add(method); } } }); return methods.toArray(new Method[methods.size()]); } /** * This variant retrieves {@link Class#getDeclaredMethods()} from a local * cache in order to avoid the JVM's SecurityManager check and defensive * array copying. In addition, it also includes Java 8 default methods from * locally implemented interfaces, since those are effectively to be treated * just like declared methods. * * @param clazz * the class to introspect * @return the cached array of methods * @see Class#getDeclaredMethods() */ private static Method[] getDeclaredMethods(Class<?> clazz) { Method[] result = declaredMethodsCache.get(clazz); if (result == null) { Method[] declaredMethods = clazz.getDeclaredMethods(); List<Method> defaultMethods = findConcreteMethodsOnInterfaces(clazz); if (defaultMethods != null) { result = new Method[declaredMethods.length + defaultMethods.size()]; System.arraycopy(declaredMethods, 0, result, 0, declaredMethods.length); int index = declaredMethods.length; for (Method defaultMethod : defaultMethods) { result[index] = defaultMethod; index++; } } else { result = declaredMethods; } declaredMethodsCache.put(clazz, result); } return result; } private static List<Method> findConcreteMethodsOnInterfaces(Class<?> clazz) { List<Method> result = null; for (Class<?> ifc : clazz.getInterfaces()) { for (Method ifcMethod : ifc.getMethods()) { if (!Modifier.isAbstract(ifcMethod.getModifiers())) { if (result == null) { result = new LinkedList<Method>(); } result.add(ifcMethod); } } } return result; } /** * Invoke the given callback on all fields in the target class, going up the * class hierarchy to get all declared fields. * * @param clazz * the target class to analyze * @param fc * the callback to invoke for each field * @since 4.2 * @see #doWithFields */ public static void doWithLocalFields(Class<?> clazz, FieldCallback fc) { for (Field field : getDeclaredFields(clazz)) { try { fc.doWith(field); } catch (IllegalAccessException ex) { throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex); } } } /** * Invoke the given callback on all fields in the target class, going up the * class hierarchy to get all declared fields. * * @param clazz * the target class to analyze * @param fc * the callback to invoke for each field */ public static void doWithFields(Class<?> clazz, FieldCallback fc) { doWithFields(clazz, fc, null); } /** * Invoke the given callback on all fields in the target class, going up the * class hierarchy to get all declared fields. * * @param clazz * the target class to analyze * @param fc * the callback to invoke for each field * @param ff * the filter that determines the fields to apply the callback to */ public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff) { // Keep backing up the inheritance hierarchy. Class<?> targetClass = clazz; do { Field[] fields = getDeclaredFields(targetClass); for (Field field : fields) { if (ff != null && !ff.matches(field)) { continue; } try { fc.doWith(field); } catch (IllegalAccessException ex) { throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex); } } targetClass = targetClass.getSuperclass(); } while (targetClass != null && targetClass != Object.class); } /** * This variant retrieves {@link Class#getDeclaredFields()} from a local * cache in order to avoid the JVM's SecurityManager check and defensive * array copying. * * @param clazz * the class to introspect * @return the cached array of fields * @see Class#getDeclaredFields() */ private static Field[] getDeclaredFields(Class<?> clazz) { Field[] result = declaredFieldsCache.get(clazz); if (result == null) { result = clazz.getDeclaredFields(); declaredFieldsCache.put(clazz, result); } return result; } /** * Given the source object and the destination, which must be the same class * or a subclass, copy all fields, including inherited fields. Designed to * work on objects with public no-arg constructors. */ public static void shallowCopyFieldState(final Object src, final Object dest) { if (src == null) { throw new IllegalArgumentException("Source for field copy cannot be null"); } if (dest == null) { throw new IllegalArgumentException("Destination for field copy cannot be null"); } if (!src.getClass().isAssignableFrom(dest.getClass())) { throw new IllegalArgumentException("Destination class [" + dest.getClass().getName() + "] must be same or subclass as source class [" + src.getClass().getName() + "]"); } doWithFields(src.getClass(), new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { makeAccessible(field); Object srcValue = field.get(src); field.set(dest, srcValue); } }, COPYABLE_FIELDS); } /** * Action to take on each method. */ public interface MethodCallback { /** * Perform an operation using the given method. * * @param method * the method to operate on */ void doWith(Method method) throws IllegalArgumentException, IllegalAccessException; } /** * Callback optionally used to filter methods to be operated on by a method * callback. */ public interface MethodFilter { /** * Determine whether the given method matches. * * @param method * the method to check */ boolean matches(Method method); } /** * Callback interface invoked on each field in the hierarchy. */ public interface FieldCallback { /** * Perform an operation using the given field. * * @param field * the field to operate on */ void doWith(Field field) throws IllegalArgumentException, IllegalAccessException; } /** * Callback optionally used to filter fields to be operated on by a field * callback. */ public interface FieldFilter { /** * Determine whether the given field matches. * * @param field * the field to check */ boolean matches(Field field); } /** * Pre-built FieldFilter that matches all non-static, non-final fields. */ public static FieldFilter COPYABLE_FIELDS = new FieldFilter() { @Override public boolean matches(Field field) { return !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())); } }; /** * Pre-built MethodFilter that matches all non-bridge methods. */ public static MethodFilter NON_BRIDGED_METHODS = new MethodFilter() { @Override public boolean matches(Method method) { return !method.isBridge(); } }; /** * Pre-built MethodFilter that matches all non-bridge methods which are not * declared on {@code java.lang.Object}. */ public static MethodFilter USER_DECLARED_METHODS = new MethodFilter() { @Override public boolean matches(Method method) { return (!method.isBridge() && method.getDeclaringClass() != Object.class); } }; }
Artur-/HotswapAgent
hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/util/ReflectionUtils.java
214,056
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; /** * Miscellaneous {@link String} utility methods. * <p/> * <p>Mainly for internal use within the framework; consider * <a href="http://jakarta.apache.org/commons/lang/">Jakarta's Commons Lang</a> * for a more comprehensive suite of String utilities. * <p/> * <p>This class delivers some simple functionality that should really * be provided by the core Java {@code String} and {@link StringBuilder} * classes, such as the ability to {@link #replace} all occurrences of a given * substring in a target string. It also provides easy-to-use methods to convert * between delimited strings, such as CSV strings, and collections and arrays. * * @author Rod Johnson * @author Juergen Hoeller * @author Keith Donald * @author Rob Harrop * @author Rick Evans * @author Arjen Poutsma * @since 16 April 2001 */ abstract class StringUtils { private static final String FOLDER_SEPARATOR = "/"; private static final String WINDOWS_FOLDER_SEPARATOR = "\\"; private static final String TOP_PATH = ".."; private static final String CURRENT_PATH = "."; private static final char EXTENSION_SEPARATOR = '.'; //--------------------------------------------------------------------- // General convenience methods for working with Strings //--------------------------------------------------------------------- /** * Check whether the given String is empty. * <p>This method accepts any Object as an argument, comparing it to * {@code null} and the empty String. As a consequence, this method * will never return {@code true} for a non-null non-String object. * <p>The Object signature is useful for general attribute handling code * that commonly deals with Strings but generally has to iterate over * Objects since attributes may e.g. be primitive value objects as well. * * @param str the candidate String * @since 3.2.1 */ public static boolean isEmpty(Object str) { return (str == null || "".equals(str)); } /** * Check that the given CharSequence is neither {@code null} nor of length 0. * Note: Will return {@code true} for a CharSequence that purely consists of whitespace. * <p><pre> * StringUtils.hasLength(null) = false * StringUtils.hasLength("") = false * StringUtils.hasLength(" ") = true * StringUtils.hasLength("Hello") = true * </pre> * * @param str the CharSequence to check (may be {@code null}) * @return {@code true} if the CharSequence is not null and has length * @see #hasText(String) */ public static boolean hasLength(CharSequence str) { return (str != null && str.length() > 0); } /** * Check that the given String is neither {@code null} nor of length 0. * Note: Will return {@code true} for a String that purely consists of whitespace. * * @param str the String to check (may be {@code null}) * @return {@code true} if the String is not null and has length * @see #hasLength(CharSequence) */ public static boolean hasLength(String str) { return hasLength((CharSequence) str); } /** * Check whether the given CharSequence has actual text. * More specifically, returns {@code true} if the string not {@code null}, * its length is greater than 0, and it contains at least one non-whitespace character. * <p><pre> * StringUtils.hasText(null) = false * StringUtils.hasText("") = false * StringUtils.hasText(" ") = false * StringUtils.hasText("12345") = true * StringUtils.hasText(" 12345 ") = true * </pre> * * @param str the CharSequence to check (may be {@code null}) * @return {@code true} if the CharSequence is not {@code null}, * its length is greater than 0, and it does not contain whitespace only * @see Character#isWhitespace */ public static boolean hasText(CharSequence str) { if (!hasLength(str)) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * Check whether the given String has actual text. * More specifically, returns {@code true} if the string not {@code null}, * its length is greater than 0, and it contains at least one non-whitespace character. * * @param str the String to check (may be {@code null}) * @return {@code true} if the String is not {@code null}, its length is * greater than 0, and it does not contain whitespace only * @see #hasText(CharSequence) */ public static boolean hasText(String str) { return hasText((CharSequence) str); } /** * Check whether the given CharSequence contains any whitespace characters. * * @param str the CharSequence to check (may be {@code null}) * @return {@code true} if the CharSequence is not empty and * contains at least 1 whitespace character * @see Character#isWhitespace */ public static boolean containsWhitespace(CharSequence str) { if (!hasLength(str)) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * Check whether the given String contains any whitespace characters. * * @param str the String to check (may be {@code null}) * @return {@code true} if the String is not empty and * contains at least 1 whitespace character * @see #containsWhitespace(CharSequence) */ public static boolean containsWhitespace(String str) { return containsWhitespace((CharSequence) str); } /** * Trim leading and trailing whitespace from the given String. * * @param str the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { sb.deleteCharAt(0); } while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } /** * Trim <i>all</i> whitespace from the given String: * leading, trailing, and inbetween characters. * * @param str the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimAllWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); int index = 0; while (sb.length() > index) { if (Character.isWhitespace(sb.charAt(index))) { sb.deleteCharAt(index); } else { index++; } } return sb.toString(); } /** * Trim leading whitespace from the given String. * * @param str the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimLeadingWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { sb.deleteCharAt(0); } return sb.toString(); } /** * Trim trailing whitespace from the given String. * * @param str the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimTrailingWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } /** * Trim all occurences of the supplied leading character from the given String. * * @param str the String to check * @param leadingCharacter the leading character to be trimmed * @return the trimmed String */ public static String trimLeadingCharacter(String str, char leadingCharacter) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) { sb.deleteCharAt(0); } return sb.toString(); } /** * Trim all occurences of the supplied trailing character from the given String. * * @param str the String to check * @param trailingCharacter the trailing character to be trimmed * @return the trimmed String */ public static String trimTrailingCharacter(String str, char trailingCharacter) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } /** * Test if the given String starts with the specified prefix, * ignoring upper/lower case. * * @param str the String to check * @param prefix the prefix to look for * @see java.lang.String#startsWith */ public static boolean startsWithIgnoreCase(String str, String prefix) { if (str == null || prefix == null) { return false; } if (str.startsWith(prefix)) { return true; } if (str.length() < prefix.length()) { return false; } String lcStr = str.substring(0, prefix.length()).toLowerCase(); String lcPrefix = prefix.toLowerCase(); return lcStr.equals(lcPrefix); } /** * Test if the given String ends with the specified suffix, * ignoring upper/lower case. * * @param str the String to check * @param suffix the suffix to look for * @see java.lang.String#endsWith */ public static boolean endsWithIgnoreCase(String str, String suffix) { if (str == null || suffix == null) { return false; } if (str.endsWith(suffix)) { return true; } if (str.length() < suffix.length()) { return false; } String lcStr = str.substring(str.length() - suffix.length()).toLowerCase(); String lcSuffix = suffix.toLowerCase(); return lcStr.equals(lcSuffix); } /** * Test whether the given string matches the given substring * at the given index. * * @param str the original string (or StringBuilder) * @param index the index in the original string to start matching against * @param substring the substring to match at the given index */ public static boolean substringMatch(CharSequence str, int index, CharSequence substring) { for (int j = 0; j < substring.length(); j++) { int i = index + j; if (i >= str.length() || str.charAt(i) != substring.charAt(j)) { return false; } } return true; } /** * Count the occurrences of the substring in string s. * * @param str string to search in. Return 0 if this is null. * @param sub string to search for. Return 0 if this is null. */ public static int countOccurrencesOf(String str, String sub) { if (str == null || sub == null || str.length() == 0 || sub.length() == 0) { return 0; } int count = 0; int pos = 0; int idx; while ((idx = str.indexOf(sub, pos)) != -1) { ++count; pos = idx + sub.length(); } return count; } /** * Replace all occurences of a substring within a string with * another string. * * @param inString String to examine * @param oldPattern String to replace * @param newPattern String to insert * @return a String with the replacements */ public static String replace(String inString, String oldPattern, String newPattern) { if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) { return inString; } StringBuilder sb = new StringBuilder(); int pos = 0; // our position in the old string int index = inString.indexOf(oldPattern); // the index of an occurrence we've found, or -1 int patLen = oldPattern.length(); while (index >= 0) { sb.append(inString.substring(pos, index)); sb.append(newPattern); pos = index + patLen; index = inString.indexOf(oldPattern, pos); } sb.append(inString.substring(pos)); // remember to append any characters to the right of a match return sb.toString(); } /** * Delete all occurrences of the given substring. * * @param inString the original String * @param pattern the pattern to delete all occurrences of * @return the resulting String */ public static String delete(String inString, String pattern) { return replace(inString, pattern, ""); } /** * Delete any character in a given String. * * @param inString the original String * @param charsToDelete a set of characters to delete. * E.g. "az\n" will delete 'a's, 'z's and new lines. * @return the resulting String */ public static String deleteAny(String inString, String charsToDelete) { if (!hasLength(inString) || !hasLength(charsToDelete)) { return inString; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < inString.length(); i++) { char c = inString.charAt(i); if (charsToDelete.indexOf(c) == -1) { sb.append(c); } } return sb.toString(); } //--------------------------------------------------------------------- // Convenience methods for working with formatted Strings //--------------------------------------------------------------------- /** * Quote the given String with single quotes. * * @param str the input String (e.g. "myString") * @return the quoted String (e.g. "'myString'"), * or {@code null} if the input was {@code null} */ public static String quote(String str) { return (str != null ? "'" + str + "'" : null); } /** * Turn the given Object into a String with single quotes * if it is a String; keeping the Object as-is else. * * @param obj the input Object (e.g. "myString") * @return the quoted String (e.g. "'myString'"), * or the input object as-is if not a String */ public static Object quoteIfString(Object obj) { return (obj instanceof String ? quote((String) obj) : obj); } /** * Unqualify a string qualified by a '.' dot character. For example, * "this.name.is.qualified", returns "qualified". * * @param qualifiedName the qualified name */ public static String unqualify(String qualifiedName) { return unqualify(qualifiedName, '.'); } /** * Unqualify a string qualified by a separator character. For example, * "this:name:is:qualified" returns "qualified" if using a ':' separator. * * @param qualifiedName the qualified name * @param separator the separator */ public static String unqualify(String qualifiedName, char separator) { return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1); } /** * Capitalize a {@code String}, changing the first letter to * upper case as per {@link Character#toUpperCase(char)}. * No other letters are changed. * * @param str the String to capitalize, may be {@code null} * @return the capitalized String, {@code null} if null */ public static String capitalize(String str) { return changeFirstCharacterCase(str, true); } /** * Uncapitalize a {@code String}, changing the first letter to * lower case as per {@link Character#toLowerCase(char)}. * No other letters are changed. * * @param str the String to uncapitalize, may be {@code null} * @return the uncapitalized String, {@code null} if null */ public static String uncapitalize(String str) { return changeFirstCharacterCase(str, false); } private static String changeFirstCharacterCase(String str, boolean capitalize) { if (str == null || str.length() == 0) { return str; } StringBuilder sb = new StringBuilder(str.length()); if (capitalize) { sb.append(Character.toUpperCase(str.charAt(0))); } else { sb.append(Character.toLowerCase(str.charAt(0))); } sb.append(str.substring(1)); return sb.toString(); } /** * Extract the filename from the given path, * e.g. "mypath/myfile.txt" -> "myfile.txt". * * @param path the file path (may be {@code null}) * @return the extracted filename, or {@code null} if none */ public static String getFilename(String path) { if (path == null) { return null; } int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR); return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path); } /** * Extract the filename extension from the given path, * e.g. "mypath/myfile.txt" -> "txt". * * @param path the file path (may be {@code null}) * @return the extracted filename extension, or {@code null} if none */ public static String getFilenameExtension(String path) { if (path == null) { return null; } int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); if (extIndex == -1) { return null; } int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR); if (folderIndex > extIndex) { return null; } return path.substring(extIndex + 1); } /** * Strip the filename extension from the given path, * e.g. "mypath/myfile.txt" -> "mypath/myfile". * * @param path the file path (may be {@code null}) * @return the path with stripped filename extension, * or {@code null} if none */ public static String stripFilenameExtension(String path) { if (path == null) { return null; } int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); if (extIndex == -1) { return path; } int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR); if (folderIndex > extIndex) { return path; } return path.substring(0, extIndex); } /** * Apply the given relative path to the given path, * assuming standard Java folder separation (i.e. "/" separators). * * @param path the path to start from (usually a full file path) * @param relativePath the relative path to apply * (relative to the full file path above) * @return the full file path that results from applying the relative path */ public static String applyRelativePath(String path, String relativePath) { int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR); if (separatorIndex != -1) { String newPath = path.substring(0, separatorIndex); if (!relativePath.startsWith(FOLDER_SEPARATOR)) { newPath += FOLDER_SEPARATOR; } return newPath + relativePath; } else { return relativePath; } } /** * Normalize the path by suppressing sequences like "path/.." and * inner simple dots. * <p>The result is convenient for path comparison. For other uses, * notice that Windows separators ("\") are replaced by simple slashes. * * @param path the original path * @return the normalized path */ public static String cleanPath(String path) { if (path == null) { return null; } String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); // Strip prefix from path to analyze, to not treat it as part of the // first path element. This is necessary to correctly parse paths like // "file:core/../core/io/Resource.class", where the ".." should just // strip the first "core" directory while keeping the "file:" prefix. int prefixIndex = pathToUse.indexOf(":"); String prefix = ""; if (prefixIndex != -1) { prefix = pathToUse.substring(0, prefixIndex + 1); pathToUse = pathToUse.substring(prefixIndex + 1); } if (pathToUse.startsWith(FOLDER_SEPARATOR)) { prefix = prefix + FOLDER_SEPARATOR; pathToUse = pathToUse.substring(1); } String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR); List<String> pathElements = new LinkedList<String>(); int tops = 0; for (int i = pathArray.length - 1; i >= 0; i--) { String element = pathArray[i]; if (CURRENT_PATH.equals(element)) { // Points to current directory - drop it. } else if (TOP_PATH.equals(element)) { // Registering top path found. tops++; } else { if (tops > 0) { // Merging path element with element corresponding to top path. tops--; } else { // Normal path element found. pathElements.add(0, element); } } } // Remaining top paths need to be retained. for (int i = 0; i < tops; i++) { pathElements.add(0, TOP_PATH); } return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR); } /** * Compare two paths after normalization of them. * * @param path1 first path for comparison * @param path2 second path for comparison * @return whether the two paths are equivalent after normalization */ public static boolean pathEquals(String path1, String path2) { return cleanPath(path1).equals(cleanPath(path2)); } /** * Parse the given {@code localeString} value into a {@link Locale}. * <p>This is the inverse operation of {@link Locale#toString Locale's toString}. * * @param localeString the locale string, following {@code Locale's} * {@code toString()} format ("en", "en_UK", etc); * also accepts spaces as separators, as an alternative to underscores * @return a corresponding {@code Locale} instance */ public static Locale parseLocaleString(String localeString) { String[] parts = tokenizeToStringArray(localeString, "_ ", false, false); String language = (parts.length > 0 ? parts[0] : ""); String country = (parts.length > 1 ? parts[1] : ""); validateLocalePart(language); validateLocalePart(country); String variant = ""; if (parts.length >= 2) { // There is definitely a variant, and it is everything after the country // code sans the separator between the country code and the variant. int endIndexOfCountryCode = localeString.lastIndexOf(country) + country.length(); // Strip off any leading '_' and whitespace, what's left is the variant. variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode)); if (variant.startsWith("_")) { variant = trimLeadingCharacter(variant, '_'); } } return (language.length() > 0 ? new Locale(language, country, variant) : null); } private static void validateLocalePart(String localePart) { for (int i = 0; i < localePart.length(); i++) { char ch = localePart.charAt(i); if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) { throw new IllegalArgumentException( "Locale part \"" + localePart + "\" contains invalid characters"); } } } /** * Determine the RFC 3066 compliant language tag, * as used for the HTTP "Accept-Language" header. * * @param locale the Locale to transform to a language tag * @return the RFC 3066 compliant language tag as String */ public static String toLanguageTag(Locale locale) { return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : ""); } static class ObjectUtils { public static boolean isEmpty(Object object) { return true; } public static String nullSafeToString(Object o) { return null; } } //--------------------------------------------------------------------- // Convenience methods for working with String arrays //--------------------------------------------------------------------- /** * Append the given String to the given String array, returning a new array * consisting of the input array contents plus the given String. * * @param array the array to append to (can be {@code null}) * @param str the String to append * @return the new array (never {@code null}) */ public static String[] addStringToArray(String[] array, String str) { if (ObjectUtils.isEmpty(array)) { return new String[]{str}; } String[] newArr = new String[array.length + 1]; System.arraycopy(array, 0, newArr, 0, array.length); newArr[array.length] = str; return newArr; } /** * Concatenate the given String arrays into one, * with overlapping array elements included twice. * <p>The order of elements in the original arrays is preserved. * * @param array1 the first array (can be {@code null}) * @param array2 the second array (can be {@code null}) * @return the new array ({@code null} if both given arrays were {@code null}) */ public static String[] concatenateStringArrays(String[] array1, String[] array2) { if (ObjectUtils.isEmpty(array1)) { return array2; } if (ObjectUtils.isEmpty(array2)) { return array1; } String[] newArr = new String[array1.length + array2.length]; System.arraycopy(array1, 0, newArr, 0, array1.length); System.arraycopy(array2, 0, newArr, array1.length, array2.length); return newArr; } /** * Merge the given String arrays into one, with overlapping * array elements only included once. * <p>The order of elements in the original arrays is preserved * (with the exception of overlapping elements, which are only * included on their first occurrence). * * @param array1 the first array (can be {@code null}) * @param array2 the second array (can be {@code null}) * @return the new array ({@code null} if both given arrays were {@code null}) */ public static String[] mergeStringArrays(String[] array1, String[] array2) { if (ObjectUtils.isEmpty(array1)) { return array2; } if (ObjectUtils.isEmpty(array2)) { return array1; } List<String> result = new ArrayList<String>(); result.addAll(Arrays.asList(array1)); for (String str : array2) { if (!result.contains(str)) { result.add(str); } } return toStringArray(result); } /** * Turn given source String array into sorted array. * * @param array the source array * @return the sorted array (never {@code null}) */ public static String[] sortStringArray(String[] array) { if (ObjectUtils.isEmpty(array)) { return new String[0]; } Arrays.sort(array); return array; } /** * Copy the given Collection into a String array. * The Collection must contain String elements only. * * @param collection the Collection to copy * @return the String array ({@code null} if the passed-in * Collection was {@code null}) */ public static String[] toStringArray(Collection<String> collection) { if (collection == null) { return null; } return collection.toArray(new String[collection.size()]); } /** * Copy the given Enumeration into a String array. * The Enumeration must contain String elements only. * * @param enumeration the Enumeration to copy * @return the String array ({@code null} if the passed-in * Enumeration was {@code null}) */ public static String[] toStringArray(Enumeration<String> enumeration) { if (enumeration == null) { return null; } List<String> list = Collections.list(enumeration); return list.toArray(new String[list.size()]); } /** * Trim the elements of the given String array, * calling {@code String.trim()} on each of them. * * @param array the original String array * @return the resulting array (of the same size) with trimmed elements */ public static String[] trimArrayElements(String[] array) { if (ObjectUtils.isEmpty(array)) { return new String[0]; } String[] result = new String[array.length]; for (int i = 0; i < array.length; i++) { String element = array[i]; result[i] = (element != null ? element.trim() : null); } return result; } /** * Remove duplicate Strings from the given array. * Also sorts the array, as it uses a TreeSet. * * @param array the String array * @return an array without duplicates, in natural sort order */ public static String[] removeDuplicateStrings(String[] array) { if (ObjectUtils.isEmpty(array)) { return array; } Set<String> set = new TreeSet<String>(); for (String element : array) { set.add(element); } return toStringArray(set); } /** * Split a String at the first occurrence of the delimiter. * Does not include the delimiter in the result. * * @param toSplit the string to split * @param delimiter to split the string up with * @return a two element array with index 0 being before the delimiter, and * index 1 being after the delimiter (neither element includes the delimiter); * or {@code null} if the delimiter wasn't found in the given input String */ public static String[] split(String toSplit, String delimiter) { if (!hasLength(toSplit) || !hasLength(delimiter)) { return null; } int offset = toSplit.indexOf(delimiter); if (offset < 0) { return null; } String beforeDelimiter = toSplit.substring(0, offset); String afterDelimiter = toSplit.substring(offset + delimiter.length()); return new String[]{beforeDelimiter, afterDelimiter}; } /** * Take an array Strings and split each element based on the given delimiter. * A {@code Properties} instance is then generated, with the left of the * delimiter providing the key, and the right of the delimiter providing the value. * <p>Will trim both the key and value before adding them to the * {@code Properties} instance. * * @param array the array to process * @param delimiter to split each element using (typically the equals symbol) * @return a {@code Properties} instance representing the array contents, * or {@code null} if the array to process was null or empty */ public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) { return splitArrayElementsIntoProperties(array, delimiter, null); } /** * Take an array Strings and split each element based on the given delimiter. * A {@code Properties} instance is then generated, with the left of the * delimiter providing the key, and the right of the delimiter providing the value. * <p>Will trim both the key and value before adding them to the * {@code Properties} instance. * * @param array the array to process * @param delimiter to split each element using (typically the equals symbol) * @param charsToDelete one or more characters to remove from each element * prior to attempting the split operation (typically the quotation mark * symbol), or {@code null} if no removal should occur * @return a {@code Properties} instance representing the array contents, * or {@code null} if the array to process was {@code null} or empty */ public static Properties splitArrayElementsIntoProperties( String[] array, String delimiter, String charsToDelete) { if (ObjectUtils.isEmpty(array)) { return null; } Properties result = new Properties(); for (String element : array) { if (charsToDelete != null) { element = deleteAny(element, charsToDelete); } String[] splittedElement = split(element, delimiter); if (splittedElement == null) { continue; } result.setProperty(splittedElement[0].trim(), splittedElement[1].trim()); } return result; } /** * Tokenize the given String into a String array via a StringTokenizer. * Trims tokens and omits empty tokens. * <p>The given delimiters string is supposed to consist of any number of * delimiter characters. Each of those characters can be used to separate * tokens. A delimiter is always a single character; for multi-character * delimiters, consider using {@code delimitedListToStringArray} * * @param str the String to tokenize * @param delimiters the delimiter characters, assembled as String * (each of those characters is individually considered as delimiter). * @return an array of the tokens * @see java.util.StringTokenizer * @see String#trim() * @see #delimitedListToStringArray */ public static String[] tokenizeToStringArray(String str, String delimiters) { return tokenizeToStringArray(str, delimiters, true, true); } /** * Tokenize the given String into a String array via a StringTokenizer. * <p>The given delimiters string is supposed to consist of any number of * delimiter characters. Each of those characters can be used to separate * tokens. A delimiter is always a single character; for multi-character * delimiters, consider using {@code delimitedListToStringArray} * * @param str the String to tokenize * @param delimiters the delimiter characters, assembled as String * (each of those characters is individually considered as delimiter) * @param trimTokens trim the tokens via String's {@code trim} * @param ignoreEmptyTokens omit empty tokens from the result array * (only applies to tokens that are empty after trimming; StringTokenizer * will not consider subsequent delimiters as token in the first place). * @return an array of the tokens ({@code null} if the input String * was {@code null}) * @see java.util.StringTokenizer * @see String#trim() * @see #delimitedListToStringArray */ public static String[] tokenizeToStringArray( String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if (str == null) { return null; } StringTokenizer st = new StringTokenizer(str, delimiters); List<String> tokens = new ArrayList<String>(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (trimTokens) { token = token.trim(); } if (!ignoreEmptyTokens || token.length() > 0) { tokens.add(token); } } return toStringArray(tokens); } /** * Take a String which is a delimited list and convert it to a String array. * <p>A single delimiter can consists of more than one character: It will still * be considered as single delimiter string, rather than as bunch of potential * delimiter characters - in contrast to {@code tokenizeToStringArray}. * * @param str the input String * @param delimiter the delimiter between elements (this is a single delimiter, * rather than a bunch individual delimiter characters) * @return an array of the tokens in the list * @see #tokenizeToStringArray */ public static String[] delimitedListToStringArray(String str, String delimiter) { return delimitedListToStringArray(str, delimiter, null); } /** * Take a String which is a delimited list and convert it to a String array. * <p>A single delimiter can consists of more than one character: It will still * be considered as single delimiter string, rather than as bunch of potential * delimiter characters - in contrast to {@code tokenizeToStringArray}. * * @param str the input String * @param delimiter the delimiter between elements (this is a single delimiter, * rather than a bunch individual delimiter characters) * @param charsToDelete a set of characters to delete. Useful for deleting unwanted * line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String. * @return an array of the tokens in the list * @see #tokenizeToStringArray */ public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) { if (str == null) { return new String[0]; } if (delimiter == null) { return new String[]{str}; } List<String> result = new ArrayList<String>(); if ("".equals(delimiter)) { for (int i = 0; i < str.length(); i++) { result.add(deleteAny(str.substring(i, i + 1), charsToDelete)); } } else { int pos = 0; int delPos; while ((delPos = str.indexOf(delimiter, pos)) != -1) { result.add(deleteAny(str.substring(pos, delPos), charsToDelete)); pos = delPos + delimiter.length(); } if (str.length() > 0 && pos <= str.length()) { // Add rest of String, but not in case of empty input. result.add(deleteAny(str.substring(pos), charsToDelete)); } } return toStringArray(result); } /** * Convert a CSV list into an array of Strings. * * @param str the input String * @return an array of Strings, or the empty array in case of empty input */ public static String[] commaDelimitedListToStringArray(String str) { return delimitedListToStringArray(str, ","); } /** * Convenience method to convert a CSV string list to a set. * Note that this will suppress duplicates. * * @param str the input String * @return a Set of String entries in the list */ public static Set<String> commaDelimitedListToSet(String str) { Set<String> set = new TreeSet<String>(); String[] tokens = commaDelimitedListToStringArray(str); for (String token : tokens) { set.add(token); } return set; } static class CollectionUtils { public static boolean isEmpty(Object object) { return true; } } /** * Convenience method to return a Collection as a delimited (e.g. CSV) * String. E.g. useful for {@code toString()} implementations. * * @param coll the Collection to display * @param delim the delimiter to use (probably a ",") * @param prefix the String to start each element with * @param suffix the String to end each element with * @return the delimited String */ public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) { if (CollectionUtils.isEmpty(coll)) { return ""; } StringBuilder sb = new StringBuilder(); Iterator<?> it = coll.iterator(); while (it.hasNext()) { sb.append(prefix).append(it.next()).append(suffix); if (it.hasNext()) { sb.append(delim); } } return sb.toString(); } /** * Convenience method to return a Collection as a delimited (e.g. CSV) * String. E.g. useful for {@code toString()} implementations. * * @param coll the Collection to display * @param delim the delimiter to use (probably a ",") * @return the delimited String */ public static String collectionToDelimitedString(Collection<?> coll, String delim) { return collectionToDelimitedString(coll, delim, "", ""); } /** * Convenience method to return a Collection as a CSV String. * E.g. useful for {@code toString()} implementations. * * @param coll the Collection to display * @return the delimited String */ public static String collectionToCommaDelimitedString(Collection<?> coll) { return collectionToDelimitedString(coll, ","); } /** * Convenience method to return a String array as a delimited (e.g. CSV) * String. E.g. useful for {@code toString()} implementations. * * @param arr the array to display * @param delim the delimiter to use (probably a ",") * @return the delimited String */ public static String arrayToDelimitedString(Object[] arr, String delim) { if (ObjectUtils.isEmpty(arr)) { return ""; } if (arr.length == 1) { return ObjectUtils.nullSafeToString(arr[0]); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (i > 0) { sb.append(delim); } sb.append(arr[i]); } return sb.toString(); } /** * Convenience method to return a String array as a CSV String. * E.g. useful for {@code toString()} implementations. * * @param arr the array to display * @return the delimited String */ public static String arrayToCommaDelimitedString(Object[] arr) { return arrayToDelimitedString(arr, ","); } }
goaway/Intellij-Colors-Sublime-Monokai
code-samples/java.java
214,057
package jsat.datatransform; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import jsat.DataSet; import jsat.classifiers.DataPoint; import jsat.distributions.Distribution; import jsat.distributions.LogUniform; import jsat.linear.DenseMatrix; import jsat.linear.DenseVector; import jsat.linear.IndexValue; import jsat.linear.Matrix; import jsat.linear.RandomMatrix; import jsat.linear.Vec; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.IntList; import jsat.utils.random.RandomUtil; /** * The Johnson-Lindenstrauss (JL) Transform is a type of random projection down * to a lower dimensional space. The goal is, with a high probability, to keep * the {@link EuclideanDistance Euclidean distances} between points * approximately the same in the original and projected space. <br> * The JL lemma, with a high probability, bounds the error of a distance * computation between two points <i>u</i> and <i>v</i> in the lower dimensional * space by (1 &plusmn; &epsilon;) d(<i>u</i>, <i>v</i>)<sup>2</sup>, where d is * the Euclidean distance. It works best for very high dimension problems, 1000 * or more. * <br> * For more information see: <br> * Achlioptas, D. (2003). <i>Database-friendly random projections: * Johnson-Lindenstrauss with binary coins</i>. Journal of Computer and System * Sciences, 66(4), 671–687. doi:10.1016/S0022-0000(03)00025-4 * * @author Edward Raff */ public class JLTransform extends DataTransformBase { private static final long serialVersionUID = -8621368067861343913L; /** * Determines which distribution to construct the transform matrix from */ public enum TransformMode { /** * The transform matrix values come from the gaussian distribution and * is dense <br><br> * This transform is expensive to use when not using an in memory matrix */ GAUSS, /** * The transform matrix values are binary and faster to generate. */ BINARY, /** * The transform matrix values are sparse, using the original "Data Base * Friendly" transform approach. */ SPARSE, /** * The transform matrix is sparser, making it faster to apply. For most * all datasets should provide results of equal quality to * {@link #SPARSE} option while being faster. */ SPARSE_SQRT, /** * The transform matrix is highly sparse, making it exceptionally fast * for larger datasets. However, accuracy may be reduced for some * problems. */ SPARSE_LOG } /** * This is used to make the Sparse JL option run faster by avoiding FLOPS. * <br> * There will be one IntList for every feature in the feature set. Each * IntList value, abs(j), indicates which of the transformed indecies * feature i will contribute value to. The sign of sign(j) indicates if it * should be additive or subtractive. */ private List<IntList> sparse_jl_map; private double sparse_jl_cnst; private TransformMode mode; private Matrix R; /** * Copy constructor * @param transform the transform to copy */ protected JLTransform(JLTransform transform) { this.mode = transform.mode; this.R = transform.R.clone(); this.k = transform.k; if(transform.sparse_jl_map != null) { this.sparse_jl_map = new ArrayList<>(transform.sparse_jl_map.size()); for(IntList a : transform.sparse_jl_map) this.sparse_jl_map.add(new IntList(a)); } this.sparse_jl_cnst = transform.sparse_jl_cnst; } /** * Creates a new JL Transform that uses a target dimension of 50 features. * This may not be optimal for any particular dataset. * */ public JLTransform() { this(50); } /** * Creates a new JL Transform * @param k the target dimension size */ public JLTransform(final int k) { this(k, TransformMode.SPARSE_SQRT); } /** * Creates a new JL Transform * @param k the target dimension size * @param mode how to construct the transform * @param rand the source of randomness */ public JLTransform(final int k, final TransformMode mode) { this(k, mode, true); } /** * Target dimension size */ private int k; private boolean inMemory; /** * Creates a new JL Transform * @param k the target dimension size * @param mode how to construct the transform * @param inMemory if {@code false}, the matrix will be stored in O(1) * memory at the cost of execution time. */ public JLTransform(final int k, final TransformMode mode, boolean inMemory) { this.mode = mode; this.k = k; this.inMemory = inMemory; } @Override public void fit(DataSet data) { final int d = data.getNumNumericalVars(); Random rand = RandomUtil.getRandom(); Matrix oldR = R = new RandomMatrixJL(k, d, rand.nextLong(), mode); if(mode == TransformMode.GAUSS) { if(inMemory) { R = new DenseMatrix(k, d); R.mutableAdd(oldR); } } else//Sparse case! Lets do this smarter { int s; switch(mode) { case SPARSE_SQRT: s = (int) Math.round(Math.sqrt(d+1)); break; case SPARSE_LOG: s = (int) Math.round(d/Math.log(d+1)); break; default://default case, use original SPARSE JL algo s = 3; } sparse_jl_cnst = Math.sqrt(s); //Lets set up some random mats. sparse_jl_map = new ArrayList<>(d); IntList all_embed_dims = IntList.range(0, k); int nnz = k/s; for(int j = 0; j < d; j++) { Collections.shuffle(all_embed_dims, rand); IntList x_j_map = new IntList(nnz); //First 1/(2 s) become the positives for(int i = 0; i < nnz; i++) x_j_map.add(i); //Second 1/(2 s) become the negatives for(int i = nnz/2; i < nnz; i++) x_j_map.add(-(i+1));//+1 b/c -0 would be a problem, since it does not exist //Sort this after so that the later use of this iteration order is better behaved for CPU cache & prefetching Collections.sort(x_j_map, (Integer o1, Integer o2) -> Integer.compare(Math.abs(o1), Math.abs(o2))); sparse_jl_map.add(x_j_map); } } } /** * The JL transform uses a random matrix to project the data, and the mode * controls which method is used to construct this matrix. * * @param mode how to construct the transform */ public void setMode(TransformMode mode) { this.mode = mode; } /** * * @return how to construct the transform */ public TransformMode getMode() { return mode; } /** * Sets whether or not the transform matrix is stored explicitly in memory * or not. Explicit storage is often faster, but can be prohibitive for * large datasets * @param inMemory {@code true} to explicitly store the transform matrix, * {@code false} to re-create it on the fly as needed */ public void setInMemory(boolean inMemory) { this.inMemory = inMemory; } /** * * @return {@code true} if this object will explicitly store the transform * matrix, {@code false} to re-create it on the fly as needed */ public boolean isInMemory() { return inMemory; } /** * Sets the target dimension size to use for the output * @param k the dimension after apply the transform */ public void setProjectedDimension(int k) { this.k = k; } /** * * @return the dimension after apply the transform */ public int getProjectedDimension() { return k; } public static Distribution guessProjectedDimension(DataSet d) { //huristic, could be improved by some theory app double max = 100; double min = 10; if(d.getNumNumericalVars() > 10000) { min = 100; max = 1000; } return new LogUniform(min, max); } @Override public DataPoint transform(DataPoint dp) { Vec newVec; switch(mode) { case SPARSE: case SPARSE_SQRT: case SPARSE_LOG: //Sparse JL case, do adds and final mul newVec = new DenseVector(k); for(IndexValue iv : dp.getNumericalValues()) { double x_i = iv.getValue(); int i = iv.getIndex(); for(int j : sparse_jl_map.get(i)) { if(j >= 0) newVec.increment(j, x_i); else newVec.increment(-j-1, -x_i); } newVec.mutableMultiply(sparse_jl_cnst); } break; default://default case, do the explicity mat-mul newVec = dp.getNumericalValues(); newVec = R.multiply(newVec); } DataPoint newDP = new DataPoint(newVec, dp.getCategoricalValues(), dp.getCategoricalData()); return newDP; } @Override public JLTransform clone() { return new JLTransform(this); } private static class RandomMatrixJL extends RandomMatrix { private static final long serialVersionUID = 2009377824896155918L; public double cnst; private TransformMode mode; public RandomMatrixJL(RandomMatrixJL toCopy) { super(toCopy); this.cnst = toCopy.cnst; this.mode = toCopy.mode; } public RandomMatrixJL(int rows, int cols, long XORSeed, TransformMode mode) { super(rows, cols, XORSeed); this.mode = mode; int k = rows; if (mode == TransformMode.GAUSS || mode == TransformMode.BINARY) cnst = 1.0 / Math.sqrt(k); else if (mode == TransformMode.SPARSE) cnst = Math.sqrt(3) / Math.sqrt(k); } @Override protected double getVal(Random rand) { if (mode == TransformMode.GAUSS) { return rand.nextGaussian()*cnst; } else if (mode == TransformMode.BINARY) { return (rand.nextBoolean() ? -cnst : cnst); } else if (mode == TransformMode.SPARSE) { int val = rand.nextInt(6); //1 with prob 1/6, -1 with prob 1/6 if(val == 0) return -cnst; else if(val == 1) return cnst; else //0 with prob 2/3 return 0; } else throw new RuntimeException("BUG: Please report"); } @Override public RandomMatrixJL clone() { return new RandomMatrixJL(this); } } }
EdwardRaff/JSAT
JSAT/src/jsat/datatransform/JLTransform.java
214,058
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans; import org.springframework.core.NestedRuntimeException; import org.springframework.util.ObjectUtils; /** * Abstract superclass for all exceptions thrown in the beans package * and subpackages. * * <p>Note that this is a runtime (unchecked) exception. Beans exceptions * are usually fatal; there is no reason for them to be checked. * * @author Rod Johnson * @author Juergen Hoeller */ @SuppressWarnings("serial") public abstract class BeansException extends NestedRuntimeException { /** * Create a new BeansException with the specified message. * @param msg the detail message */ public BeansException(String msg) { super(msg); } /** * Create a new BeansException with the specified message * and root cause. * @param msg the detail message * @param cause the root cause */ public BeansException(String msg, Throwable cause) { super(msg, cause); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof BeansException)) { return false; } BeansException otherBe = (BeansException) other; return (getMessage().equals(otherBe.getMessage()) && ObjectUtils.nullSafeEquals(getCause(), otherBe.getCause())); } @Override public int hashCode() { return getMessage().hashCode(); } }
jinchihe/blog_demos
springbeans_modify/src/main/java/org/springframework/beans/BeansException.java
214,059
/* * Copyright 2002-2019 Drew Noakes and contributors * * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ package com.drew.metadata.exif.makernotes; import com.drew.lang.annotations.Nullable; import com.drew.metadata.MetadataException; import com.drew.metadata.TagDescriptor; /** * @author Bob Johnson */ public class AppleRunTimeMakernoteDescriptor extends TagDescriptor<AppleRunTimeMakernoteDirectory> { public AppleRunTimeMakernoteDescriptor(AppleRunTimeMakernoteDirectory directory) { super(directory); } @Override @Nullable public String getDescription(int tagType) { switch (tagType) { case AppleRunTimeMakernoteDirectory.CMTimeFlags: return getFlagsDescription(); case AppleRunTimeMakernoteDirectory.CMTimeValue: return getValueDescription(); default: return super.getDescription(tagType); } } // flags bitmask details // 0000 0001 = Valid // 0000 0010 = Rounded // 0000 0100 = Positive Infinity // 0000 1000 = Negative Infinity // 0001 0000 = Indefinite @Nullable public String getFlagsDescription() { try { final int value = _directory.getInt(AppleRunTimeMakernoteDirectory.CMTimeFlags); StringBuilder sb = new StringBuilder(); if ((value & 0x1) == 1) sb.append("Valid"); else sb.append("Invalid"); if ((value & 0x2) != 0) sb.append(", rounded"); if ((value & 0x4) != 0) sb.append(", positive infinity"); if ((value & 0x8) != 0) sb.append(", negative infinity"); if ((value & 0x10) != 0) sb.append(", indefinite"); return sb.toString(); } catch (MetadataException ignored) { return null; } } @Nullable public String getValueDescription() { try { long value = _directory.getLong(AppleRunTimeMakernoteDirectory.CMTimeValue); long scale = _directory.getLong(AppleRunTimeMakernoteDirectory.CMTimeScale); return String.format("%d seconds", (value / scale)); } catch (MetadataException ignored) { return null; } } }
drewnoakes/metadata-extractor
Source/com/drew/metadata/exif/makernotes/AppleRunTimeMakernoteDescriptor.java
214,060
/** * Copyright 2010 Richard Johnson & Orin Eman * * 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. * * --- * * This file is part of java-libpst. * * java-libpst 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. * * java-libpst 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 java-libpst. If not, see <http://www.gnu.org/licenses/>. * */ package com.pff; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.HashMap; /** * Class containing attachment information. * * @author Richard Johnson */ public class PSTAttachment extends PSTObject { PSTAttachment(final PSTFile theFile, final PSTTableBC table, final HashMap<Integer, PSTDescriptorItem> localDescriptorItems) { super(theFile, null, table, localDescriptorItems); } public int getSize() { return this.getIntItem(0x0e20); } @Override public Date getCreationTime() { return this.getDateItem(0x3007); } public Date getModificationTime() { return this.getDateItem(0x3008); } public PSTMessage getEmbeddedPSTMessage() throws IOException, PSTException { PSTNodeInputStream in = null; if (this.getIntItem(0x3705) == PSTAttachment.ATTACHMENT_METHOD_EMBEDDED) { final PSTTableBCItem item = this.items.get(0x3701); if (item.entryValueType == 0x0102) { if (!item.isExternalValueReference) { in = new PSTNodeInputStream(this.pstFile, item.data); } else { // We are in trouble! throw new PSTException("External reference in getEmbeddedPSTMessage()!\n"); } } else if (item.entryValueType == 0x000D) { final int descriptorItem = (int) PSTObject.convertLittleEndianBytesToLong(item.data, 0, 4); // PSTObject.printHexFormatted(item.data, true); final PSTDescriptorItem descriptorItemNested = this.localDescriptorItems.get(descriptorItem); in = new PSTNodeInputStream(this.pstFile, descriptorItemNested); if (descriptorItemNested.subNodeOffsetIndexIdentifier > 0) { this.localDescriptorItems .putAll(this.pstFile .getPSTDescriptorItems(descriptorItemNested.subNodeOffsetIndexIdentifier)); } /* * if ( descriptorItemNested != null ) { * try { * data = descriptorItemNested.getData(); * blockOffsets = descriptorItemNested.getBlockOffsets(); * } catch (Exception e) { * e.printStackTrace(); * * data = null; * blockOffsets = null; * } * } * */ } if (in == null) { return null; } try { final PSTTableBC attachmentTable = new PSTTableBC(in); return PSTObject.createAppropriatePSTMessageObject(this.pstFile, this.descriptorIndexNode, attachmentTable, this.localDescriptorItems); } catch (final PSTException e) { e.printStackTrace(); } return null; } return null; } public InputStream getFileInputStream() throws IOException, PSTException { final PSTTableBCItem attachmentDataObject = this.items.get(0x3701); if (attachmentDataObject.isExternalValueReference) { final PSTDescriptorItem descriptorItemNested = this.localDescriptorItems .get(attachmentDataObject.entryValueReference); return new PSTNodeInputStream(this.pstFile, descriptorItemNested); } else { // internal value references are never encrypted return new PSTNodeInputStream(this.pstFile, attachmentDataObject.data, false); } } public int getFilesize() throws PSTException, IOException { final PSTTableBCItem attachmentDataObject = this.items.get(0x3701); if (attachmentDataObject.isExternalValueReference) { final PSTDescriptorItem descriptorItemNested = this.localDescriptorItems .get(attachmentDataObject.entryValueReference); if (descriptorItemNested == null) { throw new PSTException( "missing attachment descriptor item for: " + attachmentDataObject.entryValueReference); } return descriptorItemNested.getDataSize(); } else { // raw attachment data, right there! return attachmentDataObject.data.length; } } // attachment properties /** * Attachment (short) filename ASCII or Unicode string */ public String getFilename() { return this.getStringItem(0x3704); } public static final int ATTACHMENT_METHOD_NONE = 0; public static final int ATTACHMENT_METHOD_BY_VALUE = 1; public static final int ATTACHMENT_METHOD_BY_REFERENCE = 2; public static final int ATTACHMENT_METHOD_BY_REFERENCE_RESOLVE = 3; public static final int ATTACHMENT_METHOD_BY_REFERENCE_ONLY = 4; public static final int ATTACHMENT_METHOD_EMBEDDED = 5; public static final int ATTACHMENT_METHOD_OLE = 6; /** * Attachment method Integer 32-bit signed 0 => None (No attachment) 1 => By * value 2 => By reference 3 => By reference resolve 4 => By reference only * 5 => Embedded message 6 => OLE */ public int getAttachMethod() { return this.getIntItem(0x3705); } /** * Attachment size */ public int getAttachSize() { return this.getIntItem(0x0e20); } /** * Attachment number */ public int getAttachNum() { return this.getIntItem(0x0e21); } /** * Attachment long filename ASCII or Unicode string */ public String getLongFilename() { return this.getStringItem(0x3707); } /** * Attachment (short) pathname ASCII or Unicode string */ public String getPathname() { return this.getStringItem(0x3708); } /** * Attachment Position Integer 32-bit signed */ public int getRenderingPosition() { return this.getIntItem(0x370b); } /** * Attachment long pathname ASCII or Unicode string */ public String getLongPathname() { return this.getStringItem(0x370d); } /** * Attachment mime type ASCII or Unicode string */ public String getMimeTag() { return this.getStringItem(0x370e); } /** * Attachment mime sequence */ public int getMimeSequence() { return this.getIntItem(0x3710); } /** * Attachment Content ID */ public String getContentId() { return this.getStringItem(0x3712); } /** * Attachment not available in HTML */ public boolean isAttachmentInvisibleInHtml() { final int actionFlag = this.getIntItem(0x3714); return ((actionFlag & 0x1) > 0); } /** * Attachment not available in RTF */ public boolean isAttachmentInvisibleInRTF() { final int actionFlag = this.getIntItem(0x3714); return ((actionFlag & 0x2) > 0); } /** * Attachment is MHTML REF */ public boolean isAttachmentMhtmlRef() { final int actionFlag = this.getIntItem(0x3714); return ((actionFlag & 0x4) > 0); } /** * Attachment content disposition */ public String getAttachmentContentDisposition() { return this.getStringItem(0x3716); } }
rjohnsondev/java-libpst
src/main/java/com/pff/PSTAttachment.java
214,061
/*Copyright (c) 2017 Marios Michailidis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ml.fastrgf; import io.output; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import preprocess.scaling.scaler; import utilis.XorShift128PlusRandom; import utilis.detectos; import utilis.map.intint.StringIntMap4a; import exceptions.DimensionMismatchException; import exceptions.LessThanMinimum; import matrix.fsmatrix; import matrix.smatrix; import ml.classifier; import ml.estimator; /** *<p>Wraps <a href="https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwiLya_dmq3VAhVHBcAKHRPFDxQQFggoMAA&url=https%3A%2F%2Fgithub.com%2Fbaidu%2Ffast_rgf&usg=AFQjCNEK2Se2nHYT5y-KS9TUnD1TJJafUg">fast_rgf</a>). *This particular instance is allowing only classification results. fast_rgf models are being trained via a subprocess based on the operating systems *executing the class. <b>It is expected that files will be created and their size will vary based on the volumne of the training data.</b></p> * * *<p>Information about the tunable parameters can be found <a href="https://github.com/baidu/fast_rgf/tree/master/examples">here</a> </p> * *Reference : <em>Rie Johnson and Tong Zhang. Learning Nonlinear Functions Using Regularized Greedy Forest, IEEE Trans. on Pattern Analysis and Machine Intelligence, 36:942-954, 2014.</em> * *<p><b>VERY IMPORTANT NOTE</b> This implementation may not include all fast_rgf features and the user is advised to use it directly from the source. *Also the version may not be the final and it is not certain whether it will be updated in the future as it required manual work to find all libraries and *files required that need to be included for it to run. The performance and memory consumption will also be worse than running directly . Additionally *the descritpion of the parameters may not match the one in the website, hence it is advised to <a href="https://github.com/baidu/fast_rgf/tree/master/examples">use fast_rgf online parameter thread in *github</a> for more information about them. </p></em> */ public class FRGFClassifier implements estimator,classifier { /** * Number of trees to build */ public int ntrees=100; /** * threads to use */ public int threads=1; /** * maximum number of nodes */ public int max_nodes=10; /** * maximum depth of the tree */ public int max_level=4; /** * new tree is created when leaf-nodes gain < this value * estimated gain of creating new three */ public double new_tree_gain_ratio=1.0; /** * Step size of epsilon-greedy boosting (inactive for rgf) */ public double stepsize=0.1; /** * Minimum sum of data weights for each discretized value */ public int min_bucket_weights=5; /** * Maximum bins for dense data */ public int dense_max_buckets=250; /** * Histogram bins for sparse data */ public int sparse_max_buckets=250; /** * you may try a different value in [1000,10000000] */ public double sparse_max_features=1000; /** * L1 regularization on the weights */ public double lamL1=0; /** * L2 regularization on the weights */ public double lamL2=0; /** * L2 regularization parameter for sparse data */ public double sparse_lamL2=0; /** * minimum samples in node */ public int min_sample=0; /** * minimum number of occurrences for a feature to be selected */ public int min_occurrences=0; /** * The objective has to be BINARY. */ private String Objective="BINARY"; /** * optimization method for training forest (rgf or epsilon-greedy) */ public String opt="rgf"; /** * Type of loss. could be LS, MODLS (modified least squares loss), or LOGISTIC */ public String loss="LOGISTIC"; /** * scale the copy the dataset */ public boolean copy=false; /** * seed to use */ public int seed=1; /** * Random number generator to use */ private Random random; /** * holds the name of the output model. All files produced (like predictions and model dumps) will use this as prefix. */ private String model_name=""; /** * The directory where all files should be saved */ private String usedir=""; /** * weighst to used per row(sample) */ public double [] weights; /** * if true, it prints stuff */ public boolean verbose=false; /** * Target variable in double format */ public double target[]; /***** * Initial estimates */ double initial_estimates []; /** * Target variable in 2d double format */ public double target2d[][]; /** * Target variable in fixed-size matrix format */ public double [] fstarget; /** * Target variable in sparse matrix format */ public smatrix starget; /** * How many predictors the model has */ private int columndimension=0; //return number of predictors in the model public int get_predictors(){ return columndimension; } /** * @param name : name to used as predix for all files produced from this */ public void set_model_name(String name){ this.model_name=name; } /** * @param usedir : Set the directory where all files should be saved */ public void set_usedir(String usedir){ this.usedir=usedir; } /** * Number of target-variable columns. The name is left as n_classes(same as classification for consistency) */ private int n_classes=0; /** * Name of the unique classes */ private String classes[]; /** * Target variable in String format */ public String Starget[]; public int getnumber_of_classes(){ return n_classes; } public final class SessionIdentifierGenerator { private SecureRandom random = new SecureRandom(); public String nextSessionId() { return new BigInteger(130, random).toString(32); } } /** * * @param filename : the conifiguration file name for required to run xgboost from the command line * @param datset : the dataset to be used * @param model : model dump name * @param target : file containing only target */ private void create_config_file(String filename , String datset, String model , String target){ try{ // Catch errors in I/O if necessary. // Open a file to write to. String saveFile = filename; FileWriter writer = new FileWriter(saveFile); writer.append("dtree.loss=" + this.loss + "\n"); writer.append("trn.target=" + this.Objective+ "\n"); writer.append("forest.stepsize=" + this.stepsize + "\n"); writer.append("discretize.sparse.max_buckets=" + this.sparse_max_buckets + "\n"); writer.append("dtree.min_sample=" + this.min_sample+ "\n"); writer.append("dtree.new_tree_gain_ratio=" + this.new_tree_gain_ratio + "\n"); writer.append("discretize.sparse.min_bucket_weights=" + this.min_bucket_weights + "\n"); writer.append("dtree.lamL1=" + this.lamL1 + "\n"); writer.append("dtree.lamL2=" + this.lamL2 + "\n"); writer.append("discretize.sparse.max_features=" + this.sparse_max_features + "\n"); writer.append("dtree.max_level=" + this.max_level + "\n"); writer.append("set.nthreads=" + this.threads + "\n"); writer.append("forest.ntrees=" + this.ntrees + "\n"); writer.append("dtree.max_nodes=" + this.max_nodes + "\n"); writer.append("discretize.dense.max_buckets=" + this.dense_max_buckets + "\n"); writer.append("discretize.sparse.lamL2=" + this.sparse_lamL2 + "\n"); writer.append("discretize.sparse.min_occrrences=" + this.min_occurrences + "\n"); writer.append("forest.opt=" + this.opt + "\n"); writer.append("trn.x-file_format=sparse\n"); if (this.verbose){ writer.append("set.verbose=2" + "\n"); }else { writer.append("set.verbose=0" + "\n"); } //file details writer.append(datset+ "\n"); writer.append(model+ "\n"); writer.append(target+ "\n"); writer.close(); } catch (Exception e) { throw new IllegalStateException(" failed to write the config file at: " + filename); } } /** * * @param filename : the conifiguration file name for required to run xgboost from the command line * @param datset : the dataset to be used * @param model : model dump name * @param predictionfile : where the predictions will be saved */ private void create_config_file_pred(String filename , String datset, String model, String predictionfile){ try{ // Catch errors in I/O if necessary. // Open a file to write to. String saveFile = filename; FileWriter writer = new FileWriter(saveFile); writer.append("set.nthreads=" + this.threads + "\n"); if (this.verbose){ writer.append("set.verbose=2" + "\n"); }else { writer.append("set.verbose=0" + "\n"); } //file details writer.append(datset+ "\n"); writer.append( model+ "\n"); writer.append("tst.x-file_format=sparse\n"); writer.append( "tst.output-prediction=" + predictionfile + "\n"); writer.close(); } catch (Exception e) { throw new IllegalStateException(" failed to write the config file at: " + filename); } } /** * * @param confingname : full path and name of the config file * @param istrain : if this is a train task or a prediction task */ private void create_frgf_suprocess(String confingname, boolean istrain ) { // check if file exists if (new File(confingname).exists()==false){ throw new IllegalStateException("Config file does not exist at: " + confingname); } // create the subprocess try { String operational_system=detectos.getOS(); if (!operational_system.equals("win") && !operational_system.equals("linux")&& !operational_system.equals("mac")){ throw new IllegalStateException(" The operational system is not identified as win, linux or mac which is required to run xgboost" ); } String frgf_path="lib" + File.separator + operational_system + File.separator + "frgf" + File.separator + "forest_train"; if (istrain==false){ frgf_path="lib" + File.separator + operational_system + File.separator + "frgf" + File.separator + "forest_predict"; } List<String> list = new ArrayList<String>(); list.add(frgf_path); list.add("-config=" + confingname); //start the process ProcessBuilder p = new ProcessBuilder(list); p.redirectErrorStream(true); Process sp = p.start(); BufferedReader r = new BufferedReader(new InputStreamReader(sp.getInputStream())); String line; while(true){ line = r.readLine(); if(line == null) { break; } if (this.verbose){ System.out.println(line); } } } catch (IOException e) { throw new IllegalStateException(" failed to create fast_rgf subprocess with config name " + confingname); } } /** * * @param classes : the classes to put */ public void setclasses(String[] classes ) { if (classes==null || classes.length<=0){ throw new IllegalStateException (" No classes are found"); } else { this.classes= classes; } } @Override public String[] getclasses() { if (classes==null || classes.length<=0){ throw new IllegalStateException (" No classes are found, the model needs to be fitted first"); } else { return classes; } } @Override public void AddClassnames(String[] names) { String distinctnames[]=manipulate.distinct.distinct.getstringDistinctset(names); if (distinctnames.length<2){ throw new LessThanMinimum(names.length,2); } if (distinctnames.length!=names.length){ throw new IllegalStateException (" There are duplicate values in the names of the addClasses method, dedupe before adding them"); } classes=new String[names.length]; for (int j=0; j < names.length; j++){ classes[j]=names[j]; } } /** * The object that holds the modelling data in double form in cases the user chooses this form */ private double dataset[][]; /** * The object that holds the modelling data in fsmatrix form cases the user chooses this form */ private fsmatrix fsdataset; /** * The object that holds the modelling data in smatrix form cases the user chooses this form */ private smatrix sdataset; /** * Default constructor with no data */ public FRGFClassifier(){ } /** * Default constructor with double data */ public FRGFClassifier(double data [][]){ if (data==null || data.length<=0){ throw new IllegalStateException(" There is nothing to train on" ); } dataset=data; } /** * Default constructor with fsmatrix data */ public FRGFClassifier(fsmatrix data){ if (data==null || data.GetRowDimension()<=0){ throw new IllegalStateException(" There is nothing to train on" ); } fsdataset=data; } /** * Default constructor with smatrix data */ public FRGFClassifier(smatrix data){ if (data==null || data.GetRowDimension()<=0){ throw new IllegalStateException(" There is nothing to train on" ); } sdataset=data; } public void setdata(double data [][]){ if (data==null || data.length<=0){ throw new IllegalStateException(" There is nothing to train on" ); } dataset=data; } public void setdata(fsmatrix data){ if (data==null || data.GetRowDimension()<=0){ throw new IllegalStateException(" There is nothing to train on" ); } fsdataset=data; } public void setdata(smatrix data){ if (data==null || data.GetRowDimension()<=0){ throw new IllegalStateException(" There is nothing to train on" ); } sdataset=data; } @Override public void run() { // check which object was chosen to train on if (dataset!=null){ this.fit(dataset); } else if (fsdataset!=null){ this.fit(fsdataset); } else if (sdataset!=null){ this.fit(sdataset); } else { throw new IllegalStateException(" No data structure specifed in the constructor" ); } } /** * default Serial id */ private static final long serialVersionUID = -8611561535854392960L; @Override public double[][] predict_proba(double[][] data) { File directory = new File(this.usedir + File.separator + "models"); if (! directory.exists()){ directory.mkdir(); } /* check if the Create_Logic method is run properly */ if (n_classes<2 ||new File(this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod").exists()==false ){ throw new IllegalStateException("The fit method needs to be run successfully in " + "order to create the logic before attempting scoring a new set");} if (data==null || data.length<=0){ throw new IllegalStateException(" There is nothing to score" ); } if (data[0].length!=columndimension){ throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data[0].length); } if (this.threads<=0){ this.threads=Runtime.getRuntime().availableProcessors(); if (this.threads<1){ this.threads=1; } } double predictions[][]= new double [data.length][this.n_classes]; //generate dataset smatrix X= new smatrix(data); output out = new output(); out.verbose=false; out.printsmatrix(X,this.usedir + File.separator + "models"+File.separator + this.model_name + ".test");//this.usedir + File.separator + "models"+File.separator + X=null; System.gc(); if (this.n_classes==2){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name+ ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod", this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred", "\t", 0, 0.0, false, false); for (int i =0; i <predictions.length;i++ ){ predictions[i][1]= Math.min(1.0,1.0/(1+Math.exp(-temp[i]) ) ); predictions[i][0]= 1.0-predictions[i][1]; } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name.replace(" ", "") + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); f.delete(); System.gc(); }else { for (int n=0 ; n <this.n_classes; n++){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".mod", this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred", "\t", 0, 0.0, false, false); if (temp.length!=predictions.length){ throw new IllegalStateException(" The produced score in temporary file " + this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred " + " is not of correct size" ); } for (int i =0; i <predictions.length;i++ ){ predictions[i][n]=1.0/(1+Math.exp(-temp[i]) ); } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); f.delete(); System.gc(); } for (int i =0; i <predictions.length;i++ ){ double sum=0.0; for (int j =0; j <this.n_classes;j++ ){ sum+=predictions[i][j]; } for (int j =0; j <this.n_classes;j++ ){ predictions[i][j]/=sum; } } } // create new file File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".test" ); f.delete(); System.gc(); // return the 1st prediction return predictions; } @Override public double[][] predict_proba(fsmatrix data) { File directory = new File(this.usedir + File.separator + "models"); if (! directory.exists()){ directory.mkdir(); } if (n_classes<2 ||new File(this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod").exists()==false ){ throw new IllegalStateException("The fit method needs to be run successfully in " + "order to create the logic before attempting scoring a new set");} if (data==null || data.GetRowDimension()<=0){ throw new IllegalStateException(" There is nothing to score" ); } if (data.GetColumnDimension()!=columndimension){ throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension()); } if (this.threads<=0){ this.threads=Runtime.getRuntime().availableProcessors(); if (this.threads<1){ this.threads=1; } } double predictions[][]= new double [data.GetRowDimension()][this.n_classes]; smatrix X= new smatrix(data); output out = new output(); out.verbose=false; out.printsmatrix(X,this.usedir + File.separator + "models"+File.separator + this.model_name + ".test");//this.usedir + File.separator + "models"+File.separator + X=null; System.gc(); if (this.n_classes==2){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod", this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred", "\t", 0, 0.0, false, false); for (int i =0; i <predictions.length;i++ ){ predictions[i][1]= Math.min(1.0,1.0/(1+Math.exp(-temp[i]) ) ); predictions[i][0]= 1.0-predictions[i][1]; } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+ ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); f.delete(); System.gc(); }else { for (int n=0 ; n <this.n_classes; n++){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".mod", this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred", "\t", 0, 0.0, false, false); if (temp.length!=predictions.length){ throw new IllegalStateException(" The produced score in temporary file " + this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred " + " is not of correct size" ); } for (int i =0; i <predictions.length;i++ ){ predictions[i][n]=1.0/(1+Math.exp(-temp[i]) ); } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); f.delete(); System.gc(); } for (int i =0; i <predictions.length;i++ ){ double sum=0.0; for (int j =0; j <this.n_classes;j++ ){ sum+=predictions[i][j]; } for (int j =0; j <this.n_classes;j++ ){ predictions[i][j]/=sum; } } } // create new file File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".test" ); f.delete(); System.gc(); // return the 1st prediction return predictions; } @Override public double[][] predict_proba(smatrix data) { File directory = new File(this.usedir + File.separator + "models"); if (! directory.exists()){ directory.mkdir(); } /* * check if the Create_Logic method is run properly */ if (n_classes<2 ||new File(this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod").exists()==false ){ throw new IllegalStateException("The fit method needs to be run successfully in " + "order to create the logic before attempting scoring a new set");} if (data==null || data.GetRowDimension()<=0){ throw new IllegalStateException(" There is nothing to score" ); } if (data.GetColumnDimension()!=columndimension){ throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension()); } if (this.threads<=0){ this.threads=Runtime.getRuntime().availableProcessors(); if (this.threads<1){ this.threads=1; } } if (!data.IsSortedByRow()){ data.convert_type(); } double predictions[][]= new double [data.GetRowDimension()][this.n_classes]; output out = new output(); out.verbose=false; out.printsmatrix(data,this.usedir + File.separator + "models"+File.separator + this.model_name + ".test");//this.usedir + File.separator + "models"+File.separator + if (this.n_classes==2){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod", this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred", "\t", 0, 0.0, false, false); for (int i =0; i <predictions.length;i++ ){ predictions[i][1]= Math.min(1.0,1.0/(1+Math.exp(-temp[i]) ) ); predictions[i][0]= 1.0-predictions[i][1]; } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); f.delete(); System.gc(); }else { for (int n=0 ; n <this.n_classes; n++){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".mod", this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred", "\t", 0, 0.0, false, false); if (temp.length!=predictions.length){ throw new IllegalStateException(" The produced score in temporary file " + this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred " + " is not of correct size" ); } for (int i =0; i <predictions.length;i++ ){ predictions[i][n]=1.0/(1+Math.exp(-temp[i]) ); } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); f.delete(); System.gc(); } for (int i =0; i <predictions.length;i++ ){ double sum=0.0; for (int j =0; j <this.n_classes;j++ ){ sum+=predictions[i][j]; } for (int j =0; j <this.n_classes;j++ ){ predictions[i][j]/=sum; } } } // create new file File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".test" ); f.delete(); System.gc(); // return the 1st prediction return predictions; } @Override public double[] predict_probaRow(double[] data) { return null; } @Override public double[] predict_probaRow(fsmatrix data, int rows) { return null; } @Override public double[] predict_probaRow(smatrix data, int start, int end) { return null; } @Override public double[] predict(fsmatrix data) { File directory = new File(this.usedir + File.separator + "models"); if (! directory.exists()){ directory.mkdir(); } /* * check if the Create_Logic method is run properly */ if (n_classes<2 ||new File(this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod").exists()==false ){ throw new IllegalStateException("The fit method needs to be run successfully in " + "order to create the logic before attempting scoring a new set");} if (data==null || data.GetRowDimension()<=0){ throw new IllegalStateException(" There is nothing to score" ); } if (data.GetColumnDimension()!=columndimension){ throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension()); } if (this.threads<=0){ this.threads=Runtime.getRuntime().availableProcessors(); if (this.threads<1){ this.threads=1; } } double predictions[]= new double [data.GetRowDimension()]; double prediction_probas[][]= new double [data.GetRowDimension()][n_classes]; smatrix X= new smatrix(data); output out = new output(); out.verbose=false; out.printsmatrix(X,this.usedir + File.separator + "models"+File.separator + this.model_name + ".test");//this.usedir + File.separator + "models"+File.separator + X=null; System.gc(); if (this.n_classes==2){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name.replace(" ", "") + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod", this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred", "\t", 0, 0.0, false, false); for (int i =0; i <predictions.length;i++ ){ prediction_probas[i][1]= Math.min(1.0,1.0/(1+Math.exp(-temp[i]) ) ); prediction_probas[i][0]= 1.0-prediction_probas[i][1]; } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+ ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); f.delete(); System.gc(); }else { for (int n=0 ; n <this.n_classes; n++){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".mod", this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred", "\t", 0, 0.0, false, false); if (temp.length!=predictions.length){ throw new IllegalStateException(" The produced score in temporary file " + this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred " + " is not of correct size" ); } for (int i =0; i <predictions.length;i++ ){ prediction_probas[i][n]=temp[i]; } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); f.delete(); System.gc(); } } // create new file File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".test" ); f.delete(); System.gc(); System.gc(); // return the 1st prediction for (int i=0; i < predictions.length; i++) { double [] temp=prediction_probas[i]; int maxi=0; double max=temp[0]; for (int k=1; k<n_classes; k++) { if (temp[k]>max){ max=temp[k]; maxi=k; } } try{ predictions[i]=Double.parseDouble(classes[maxi]); } catch (Exception e){ predictions[i]=maxi; } } prediction_probas=null; // return the 1st prediction return predictions; } @Override public double[] predict(smatrix data) { File directory = new File(this.usedir + File.separator + "models"); if (! directory.exists()){ directory.mkdir(); } /* * check if the Create_Logic method is run properly */ if (n_classes<2 ||new File(this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod").exists()==false ){ throw new IllegalStateException("The fit method needs to be run successfully in " + "order to create the logic before attempting scoring a new set");} if (data==null || data.GetRowDimension()<=0){ throw new IllegalStateException(" There is nothing to score" ); } if (data.GetColumnDimension()!=columndimension){ throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension()); } if (this.threads<=0){ this.threads=Runtime.getRuntime().availableProcessors(); if (this.threads<1){ this.threads=1; } } if (!data.IsSortedByRow()){ data.convert_type(); } double predictions[]= new double [data.GetRowDimension()]; double prediction_probas[][]= new double [data.GetRowDimension()][n_classes]; output out = new output(); out.verbose=false; out.printsmatrix(data,this.usedir + File.separator + "models"+File.separator + this.model_name + ".test");//this.usedir + File.separator + "models"+File.separator + System.gc(); if (this.n_classes==2){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod", this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred", "\t", 0, 0.0, false, false); for (int i =0; i <predictions.length;i++ ){ prediction_probas[i][1]= Math.min(1.0,1.0/(1+Math.exp(-temp[i]) ) ); prediction_probas[i][0]= 1.0-prediction_probas[i][1]; } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); f.delete(); System.gc(); }else { for (int n=0 ; n <this.n_classes; n++){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".mod", this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred", "\t", 0, 0.0, false, false); if (temp.length!=predictions.length){ throw new IllegalStateException(" The produced score in temporary file " + this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred " + " is not of correct size" ); } for (int i =0; i <predictions.length;i++ ){ prediction_probas[i][n]=temp[i]; } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); f.delete(); System.gc(); } } // create new file File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".test" ); f.delete(); System.gc(); // return the 1st prediction for (int i=0; i < predictions.length; i++) { double [] temp=prediction_probas[i]; int maxi=0; double max=temp[0]; for (int k=1; k<n_classes; k++) { if (temp[k]>max){ max=temp[k]; maxi=k; } } try{ predictions[i]=Double.parseDouble(classes[maxi]); } catch (Exception e){ predictions[i]=maxi; } } prediction_probas=null; // return the 1st prediction return predictions; } @Override public double[] predict(double[][] data) { File directory = new File(this.usedir + File.separator + "models"); if (! directory.exists()){ directory.mkdir(); } /* * check if the Create_Logic method is run properly */ if (n_classes<2 ||new File(this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod").exists()==false ){ throw new IllegalStateException("The fit method needs to be run successfully in " + "order to create the logic before attempting scoring a new set");} if (data==null || data.length<=0){ throw new IllegalStateException(" There is nothing to score" ); } if (data[0].length!=columndimension){ throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data[0].length); } if (this.threads<=0){ this.threads=Runtime.getRuntime().availableProcessors(); if (this.threads<1){ this.threads=1; } } double predictions[]= new double [data.length]; double prediction_probas[][]= new double [data.length][n_classes]; smatrix X= new smatrix(data); output out = new output(); out.verbose=false; out.printsmatrix(X,this.usedir + File.separator + "models"+File.separator + this.model_name + ".test");//this.usedir + File.separator + "models"+File.separator + X=null; System.gc(); if (this.n_classes==2){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod", this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred", "\t", 0, 0.0, false, false); for (int i =0; i <predictions.length;i++ ){ prediction_probas[i][1]= Math.min(1.0,1.0/(1+Math.exp(-temp[i]) ) ); prediction_probas[i][0]= 1.0-prediction_probas[i][1]; } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".pred" ); f.delete(); System.gc(); }else { for (int n=0 ; n <this.n_classes; n++){ create_config_file_pred(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , "tst.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".test", "model.load=" +this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".mod", this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" , false); double temp []=io.input.Retrievecolumn(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred", "\t", 0, 0.0, false, false); if (temp.length!=predictions.length){ throw new IllegalStateException(" The produced score in temporary file " + this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred " + " is not of correct size" ); } for (int i =0; i <predictions.length;i++ ){ prediction_probas[i][n]=temp[i]; } temp=null; File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + n + ".pred" ); f.delete(); System.gc(); } } // create new file File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".test" ); f.delete(); System.gc(); System.gc(); // return the 1st prediction for (int i=0; i < predictions.length; i++) { double [] temp=prediction_probas[i]; int maxi=0; double max=temp[0]; for (int k=1; k<n_classes; k++) { if (temp[k]>max){ max=temp[k]; maxi=k; } } try{ predictions[i]=Double.parseDouble(classes[maxi]); } catch (Exception e){ predictions[i]=maxi; } } prediction_probas=null; // return the 1st prediction return predictions; } @Override public double predict_Row(double[] data) { return 0.0; } @Override public double predict_Row(fsmatrix data, int rows) { return 0.0; } @Override public double predict_Row(smatrix data, int start, int end) { return 0.0; } @Override public void fit(double[][] data) { // make sensible checks if (data==null || data.length<=0){ throw new IllegalStateException(" Main data object is null or has too few cases" ); } dataset=data; this.random = new XorShift128PlusRandom(this.seed); //check model name if (this.model_name.equals("")){ SessionIdentifierGenerator session = new SessionIdentifierGenerator(); this.model_name=session.nextSessionId(); } // check diretcory if (this.usedir.equals("")){ usedir=System.getProperty("user.dir"); // working directory } File directory = new File(this.usedir + File.separator + "models"); if (! directory.exists()){ directory.mkdir(); } if ( !loss.equals("LOGISTIC") && !loss.equals("LS") & !loss.equals("MODLS")){ throw new IllegalStateException(" loss has to be in 'LOGISTIC', 'LS' or 'MODLS'" ); } if ( !opt.equals("rgf") && !opt.equals("epsilon-greedy") ){ throw new IllegalStateException(" opt has to be between 'rgf' and 'epsilon-greedy'" ); } if (this.min_occurrences<0){ this.min_occurrences=1; } if (this.sparse_lamL2<0){ this.sparse_lamL2=0.1; } if (this.dense_max_buckets<0){ this.dense_max_buckets=250; } if (this.max_nodes<0){ this.max_nodes=10; } if (this.lamL1<=0){ this.lamL1=0.1; } if (this.lamL2<0){ this.lamL2=0.1; } if (this.min_bucket_weights<=0){ this.min_bucket_weights=250; } if (this.ntrees<1){ this.ntrees=50; } if (this.new_tree_gain_ratio<0){ this.new_tree_gain_ratio=1.0; } if (this.stepsize<=0){ this.stepsize=0.1; } if (this.sparse_max_features<=0){ this.sparse_max_features=1000; } if (this.max_level<=0){ this.max_level=4; } if (this.threads<0){ this.threads=Runtime.getRuntime().availableProcessors(); if (this.threads<1){ this.threads=1; } } // make sensible checks on the target data if ( (target==null || target.length!=data.length) && (Starget==null || Starget.length!=data.length) ){ throw new IllegalStateException(" target array needs to be provided with the same length as the data" ); } else if (target!=null && (classes==null || classes.length<=1) ){ // check if values only 1 and zero HashSet<Double> has= new HashSet<Double> (); for (int i=0; i < target.length; i++){ has.add(target[i]); } if (has.size()<=1){ throw new IllegalStateException(" target array needs to have more 2 or more classes" ); } double uniquevalues[]= new double[has.size()]; int k=0; for (Iterator<Double> it = has.iterator(); it.hasNext(); ) { uniquevalues[k]= it.next(); k++; } // sort values Arrays.sort(uniquevalues); classes= new String[uniquevalues.length]; StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F); int index=0; for (int j=0; j < uniquevalues.length; j++){ classes[j]=uniquevalues[j]+""; mapper.put(classes[j], index); index++; } fstarget=new double[target.length]; for (int i=0; i < fstarget.length; i++){ fstarget[i]=mapper.get(target[i] + ""); } } else if (Starget!=null && (classes==null || classes.length<=1)){ classes=manipulate.distinct.distinct.getstringDistinctset(Starget); if (classes.length<=1){ throw new IllegalStateException(" target array needs to have more 2 or more classes" ); } Arrays.sort(classes); StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F); int index=0; for (int j=0; j < classes.length; j++){ mapper.put(classes[j], index); index++; } fstarget=new double[Starget.length]; for (int i=0; i < fstarget.length; i++){ fstarget[i]=mapper.get(Starget[i]); } }else { fstarget=this.target; } if (weights==null) { /* weights=new double [data.GetRowDimension()]; for (int i=0; i < weights.length; i++){ weights[i]=1.0; } */ } else { if (weights.length!=data.length){ throw new DimensionMismatchException(weights.length,data.length); } weights=manipulate.transforms.transforms.scaleweight(weights); for (int i=0; i < weights.length; i++){ weights[i]*= weights.length; } } //hard copy if (copy){ data= manipulate.copies.copies.Copy(data); } this.n_classes=classes.length; columndimension=data[0].length; //generate config file //generate dataset smatrix X= new smatrix(data); System.out.println(X.GetColumnDimension() + X.GetRowDimension()); output out = new output(); out.verbose=false; out.printsmatrix(X,this.usedir + File.separator + "models"+File.separator + this.model_name + ".train");//this.usedir + File.separator + "models"+File.separator + X=null; if (n_classes==2){ out = new output(); out.verbose=false; out.printSingledouble(fstarget, this.usedir + File.separator + "models"+File.separator + this.model_name + ".label"); fstarget=null; create_config_file(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , "trn.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".train", "model.save=" +this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod", "trn.y-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".label"); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , true); File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".label" ); // tries to delete a non-existing file f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+ ".conf" ); // tries to delete a non-existing file f.delete(); }else { for (int n=0; n <n_classes; n++ ){ double label []= new double [fstarget.length]; for (int i=0; i < label.length; i++){ if ( fstarget[i]==Double.parseDouble(classes[n]) ){ label[i]=1.0; } else { label[i]=0.0; } } out = new output(); out.verbose=false; out.printSingledouble(label, this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".label"); label=null; create_config_file(this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".conf" , "trn.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".train", "model.save=" +this.usedir + File.separator + "models"+File.separator + this.model_name +n+".mod", "trn.y-file="+this.usedir + File.separator + "models"+File.separator + this.model_name +n+".label"); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".conf" , true); File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".label" ); // tries to delete a non-existing file f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+n+ ".conf" ); // tries to delete a non-existing file f.delete(); } } // create new file File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+ ".train" ); // tries to delete a non-existing file f.delete(); fsdataset=null; sdataset=null; System.gc(); } @Override public void fit(fsmatrix data) { // make sensible checks if (data==null || data.GetRowDimension()<=0){ throw new IllegalStateException(" Main data object is null or has too few cases" ); } fsdataset=data; this.random = new XorShift128PlusRandom(this.seed); //check model name if (this.model_name.equals("")){ SessionIdentifierGenerator session = new SessionIdentifierGenerator(); this.model_name=session.nextSessionId(); } // check diretcory if (this.usedir.equals("")){ usedir=System.getProperty("user.dir"); // working directory } File directory = new File(this.usedir + File.separator + "models"); if (! directory.exists()){ directory.mkdir(); } if ( !loss.equals("LOGISTIC") && !loss.equals("LS") & !loss.equals("MODLS")){ throw new IllegalStateException(" loss has to be in 'LOGISTIC', 'LS' or 'MODLS'" ); } if ( !opt.equals("rgf") && !opt.equals("epsilon-greedy") ){ throw new IllegalStateException(" opt has to be between 'rgf' and 'epsilon-greedy'" ); } if (this.min_occurrences<0){ this.min_occurrences=1; } if (this.sparse_lamL2<0){ this.sparse_lamL2=0.1; } if (this.dense_max_buckets<0){ this.dense_max_buckets=250; } if (this.max_nodes<0){ this.max_nodes=10; } if (this.lamL1<=0){ this.lamL1=0.1; } if (this.lamL2<0){ this.lamL2=0.1; } if (this.min_bucket_weights<=0){ this.min_bucket_weights=250; } if (this.ntrees<1){ this.ntrees=50; } if (this.new_tree_gain_ratio<0){ this.new_tree_gain_ratio=1.0; } if (this.stepsize<=0){ this.stepsize=0.1; } if (this.sparse_max_features<=0){ this.sparse_max_features=1000; } if (this.max_level<=0){ this.max_level=4; } if (this.threads<0){ this.threads=Runtime.getRuntime().availableProcessors(); if (this.threads<1){ this.threads=1; } } // make sensible checks on the target data if ( (target==null || target.length!=data.GetRowDimension()) && (Starget==null || Starget.length!=data.GetRowDimension()) ){ throw new IllegalStateException(" target array needs to be provided with the same length as the data" ); } else if (target!=null && (classes==null || classes.length<=1) ){ // check if values only 1 and zero HashSet<Double> has= new HashSet<Double> (); for (int i=0; i < target.length; i++){ has.add(target[i]); } if (has.size()<=1){ throw new IllegalStateException(" target array needs to have more 2 or more classes" ); } double uniquevalues[]= new double[has.size()]; int k=0; for (Iterator<Double> it = has.iterator(); it.hasNext(); ) { uniquevalues[k]= it.next(); k++; } // sort values Arrays.sort(uniquevalues); classes= new String[uniquevalues.length]; StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F); int index=0; for (int j=0; j < uniquevalues.length; j++){ classes[j]=uniquevalues[j]+""; mapper.put(classes[j], index); index++; } fstarget=new double[target.length]; for (int i=0; i < fstarget.length; i++){ fstarget[i]=mapper.get(target[i] + ""); } } else if (Starget!=null && (classes==null || classes.length<=1)){ classes=manipulate.distinct.distinct.getstringDistinctset(Starget); if (classes.length<=1){ throw new IllegalStateException(" target array needs to have more 2 or more classes" ); } Arrays.sort(classes); StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F); int index=0; for (int j=0; j < classes.length; j++){ mapper.put(classes[j], index); index++; } fstarget=new double[Starget.length]; for (int i=0; i < fstarget.length; i++){ fstarget[i]=mapper.get(Starget[i]); } }else { fstarget=this.target; } if (weights==null) { /* weights=new double [data.GetRowDimension()]; for (int i=0; i < weights.length; i++){ weights[i]=1.0; } */ } else { if (weights.length!=data.GetRowDimension()){ throw new DimensionMismatchException(weights.length,data.GetRowDimension()); } weights=manipulate.transforms.transforms.scaleweight(weights); for (int i=0; i < weights.length; i++){ weights[i]*= weights.length; } } //hard copy if (copy){ data= (fsmatrix) data.Copy(); } this.n_classes=classes.length; columndimension=data.GetColumnDimension(); //generate config file //generate dataset smatrix X= new smatrix(data); output out = new output(); out.verbose=false; out.printsmatrix(X,this.usedir + File.separator + "models"+File.separator + this.model_name + ".train");//this.usedir + File.separator + "models"+File.separator + X=null; if (n_classes==2){ out = new output(); out.verbose=false; out.printSingledouble(fstarget, this.usedir + File.separator + "models"+File.separator + this.model_name + ".label"); fstarget=null; create_config_file(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , "trn.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".train", "model.save=" +this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod", "trn.y-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".label"); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , true); File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".label" ); // tries to delete a non-existing file f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+ ".conf" ); // tries to delete a non-existing file f.delete(); }else { for (int n=0; n <n_classes; n++ ){ double label []= new double [fstarget.length]; for (int i=0; i < label.length; i++){ if ( fstarget[i]==Double.parseDouble(classes[n]) ){ label[i]=1.0; } else { label[i]=0.0; } } out = new output(); out.verbose=false; out.printSingledouble(label, this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".label"); label=null; create_config_file(this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".conf" , "trn.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".train", "model.save=" +this.usedir + File.separator + "models"+File.separator + this.model_name +n+".mod", "trn.y-file="+this.usedir + File.separator + "models"+File.separator + this.model_name +n+".label"); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".conf" , true); File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".label" ); // tries to delete a non-existing file f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+n+ ".conf" ); // tries to delete a non-existing file f.delete(); } } // create new file File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+ ".train" ); // tries to delete a non-existing file f.delete(); fsdataset=null; sdataset=null; System.gc(); } @Override public void fit(smatrix data) { // make sensible checks if (data==null || data.GetRowDimension()<=0){ throw new IllegalStateException(" Main data object is null or has too few cases" ); } sdataset=data; this.random = new XorShift128PlusRandom(this.seed); //check model name if (this.model_name.equals("")){ SessionIdentifierGenerator session = new SessionIdentifierGenerator(); this.model_name=session.nextSessionId(); } // check directory if (this.usedir.equals("")){ usedir=System.getProperty("user.dir"); // working directory } File directory = new File(this.usedir + File.separator + "models"); if (! directory.exists()){ directory.mkdir(); } if ( !loss.equals("LOGISTIC") && !loss.equals("LS") & !loss.equals("MODLS")){ throw new IllegalStateException(" loss has to be in 'LOGISTIC', 'LS' or 'MODLS'" ); } if ( !opt.equals("rgf") && !opt.equals("epsilon-greedy") ){ throw new IllegalStateException(" opt has to be between 'rgf' and 'epsilon-greedy'" ); } if (this.min_occurrences<0){ this.min_occurrences=1; } if (this.sparse_lamL2<0){ this.sparse_lamL2=0.1; } if (this.dense_max_buckets<0){ this.dense_max_buckets=250; } if (this.max_nodes<0){ this.max_nodes=10; } if (this.lamL1<=0){ this.lamL1=0.1; } if (this.lamL2<0){ this.lamL2=0.1; } if (this.min_bucket_weights<=0){ this.min_bucket_weights=250; } if (this.ntrees<1){ this.ntrees=50; } if (this.new_tree_gain_ratio<0){ this.new_tree_gain_ratio=1.0; } if (this.stepsize<=0){ this.stepsize=0.1; } if (this.sparse_max_features<=0){ this.sparse_max_features=1000; } if (this.max_level<=0){ this.max_level=4; } if (this.threads<0){ this.threads=Runtime.getRuntime().availableProcessors(); if (this.threads<1){ this.threads=1; } } // make sensible checks on the target data if ( (target==null || target.length!=data.GetRowDimension()) && (Starget==null || Starget.length!=data.GetRowDimension()) ){ throw new IllegalStateException(" target array needs to be provided with the same length as the data" ); } else if (target!=null && (classes==null || classes.length<=1) ){ // check if values only 1 and zero HashSet<Double> has= new HashSet<Double> (); for (int i=0; i < target.length; i++){ has.add(target[i]); } if (has.size()<=1){ throw new IllegalStateException(" target array needs to have more 2 or more classes" ); } double uniquevalues[]= new double[has.size()]; int k=0; for (Iterator<Double> it = has.iterator(); it.hasNext(); ) { uniquevalues[k]= it.next(); k++; } // sort values Arrays.sort(uniquevalues); classes= new String[uniquevalues.length]; StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F); int index=0; for (int j=0; j < uniquevalues.length; j++){ classes[j]=uniquevalues[j]+""; mapper.put(classes[j], index); index++; } fstarget=new double[target.length]; for (int i=0; i < fstarget.length; i++){ fstarget[i]=mapper.get(target[i] + ""); } } else if (Starget!=null && (classes==null || classes.length<=1)){ classes=manipulate.distinct.distinct.getstringDistinctset(Starget); if (classes.length<=1){ throw new IllegalStateException(" target array needs to have more 2 or more classes" ); } Arrays.sort(classes); StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F); int index=0; for (int j=0; j < classes.length; j++){ mapper.put(classes[j], index); index++; } fstarget=new double[Starget.length]; for (int i=0; i < fstarget.length; i++){ fstarget[i]=mapper.get(Starget[i]); } }else { fstarget=this.target; } if (weights==null) { /* weights=new double [data.GetRowDimension()]; for (int i=0; i < weights.length; i++){ weights[i]=1.0; } */ } else { if (weights.length!=data.GetRowDimension()){ throw new DimensionMismatchException(weights.length,data.GetRowDimension()); } weights=manipulate.transforms.transforms.scaleweight(weights); for (int i=0; i < weights.length; i++){ weights[i]*= weights.length; } } //hard copy if (copy){ data= (smatrix) data.Copy(); } this.n_classes=classes.length; columndimension=data.GetColumnDimension(); //generate config file //generate dataset output out = new output(); out.verbose=false; out.printsmatrix(data,this.usedir + File.separator + "models"+File.separator + this.model_name + ".train");//this.usedir + File.separator + "models"+File.separator + data=null; if (n_classes==2){ out = new output(); out.verbose=false; out.printSingledouble(fstarget, this.usedir + File.separator + "models"+File.separator + this.model_name + ".label"); fstarget=null; create_config_file(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , "trn.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".train", "model.save=" +this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod", "trn.y-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".label"); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" , true); File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".label" ); // tries to delete a non-existing file f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+ ".conf" ); // tries to delete a non-existing file f.delete(); }else { for (int n=0; n <n_classes; n++ ){ double label []= new double [fstarget.length]; for (int i=0; i < label.length; i++){ if ( fstarget[i]==Double.parseDouble(classes[n]) ){ label[i]=1.0; } else { label[i]=0.0; } } out = new output(); out.verbose=false; out.printSingledouble(label, this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".label"); label=null; create_config_file(this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".conf" , "trn.x-file="+this.usedir + File.separator + "models"+File.separator + this.model_name + ".train", "model.save=" +this.usedir + File.separator + "models"+File.separator + this.model_name +n+".mod", "trn.y-file="+this.usedir + File.separator + "models"+File.separator + this.model_name +n+".label"); //make subprocess create_frgf_suprocess(this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".conf" , true); File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name +n+ ".label" ); // tries to delete a non-existing file f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+n+ ".conf" ); // tries to delete a non-existing file f.delete(); } } // create new file File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name+ ".train" ); // tries to delete a non-existing file f.delete(); fstarget=null; fsdataset=null; sdataset=null; System.gc(); } /** * Retrieve the number of target variables */ public int getnumber_of_targets(){ return n_classes; } public double get_sum(double array []){ double a=0.0; for (int i=0; i <array.length; i++ ){ a+=array[i]; } return a; } /** * * @returns the closest integer that reflects this percentage! * <p> it may sound strange, random.nextint can be significantly faster than nextdouble() */ public int get_random_integer(double percentage){ double per= Math.min(Math.max(0, percentage),1.0); double difference=2147483647.0+(2147483648.0); int point=(int)(-2147483648.0 + (per*difference )); return point; } @Override public String GetType() { return "classifier"; } @Override public boolean SupportsWeights() { return true; } @Override public String GetName() { return "FRGFClassifier"; } @Override public void PrintInformation() { System.out.println("Classifier: FRGFClassifier"); System.out.println("Classes: " + n_classes); System.out.println("Supports Weights: True"); System.out.println("Column dimension: " + columndimension); System.out.println("loss: " + this.loss ); System.out.println("objective: " + this.Objective); System.out.println("stepsize=" + this.stepsize ); System.out.println("sparse_max_buckets=" + this.sparse_max_buckets ); System.out.println("new_tree_gain_ratio=" + this.new_tree_gain_ratio); System.out.println("min_bucket_weights=" + this.min_bucket_weights ); System.out.println("lamL1=" + this.lamL1 ); System.out.println("lamL2=" + this.lamL2 ); System.out.println("sparse_max_features=" + this.sparse_max_features ); System.out.println("max_level=" + this.max_level ); System.out.println("min_sample=" + this.min_sample ); System.out.println("threads=" + this.threads ); System.out.println("ntrees=" + this.ntrees ); System.out.println("seed=" + this.seed ); System.out.println("dense_max_buckets=" + this.dense_max_buckets ); System.out.println("sparse_lamL2=" + this.sparse_lamL2 ); System.out.println("opt=" + this.opt ); if (this.verbose){ System.out.println("verbose: true"); }else { System.out.println("verbose: false"); } if (new File(this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod").exists()){ System.out.println("Trained: True"); } else { System.out.println("Trained: False"); } } @Override public boolean HasTheSametype(estimator a) { if (a.GetType().equals(this.GetType())){ return true; } else { return false; } } @Override public boolean isfitted() { if (new File(this.usedir + File.separator + "models"+File.separator + this.model_name +"0.mod").exists()){ return true; } else { return false; } } @Override public boolean IsRegressor() { return false ; } @Override public boolean IsClassifier() { return true; } @Override public void reset() { File directory = new File(this.usedir + File.separator + "models"); if (! directory.exists()){ directory.mkdir(); } n_classes=0; threads=1; columndimension=0; // create new file File f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".train" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".conf" ); f.delete(); f = new File(this.usedir + File.separator + "models"+File.separator + this.model_name + ".mod" ); f.delete(); loss = "LOGISTIC"; Objective = ""; ntrees=100; max_nodes=10; max_level=5; sparse_max_buckets=250; new_tree_gain_ratio=0; stepsize=0.1; min_bucket_weights=5; dense_max_buckets=250; sparse_max_features=1000; lamL1=0; lamL2=0; opt="rgf"; sparse_lamL2=1; min_occurrences=5; classes=null; copy=true; seed=1; random=null; target=null; fstarget=null; target=null; fstarget=null; starget=null; weights=null; verbose=true; } @Override public estimator copy() { return this; } @Override public void set_params(String params){ String splitted_params []=params.split(" " + "+"); for (int j=0; j<splitted_params.length; j++ ){ String mini_split []=splitted_params[j].split(":"); if (mini_split.length>=2){ String metric=mini_split[0]; String value=mini_split[1]; //System.out.println("'" + metric + "'" + " value=" + value); if (metric.equals("lamL1")) {this.lamL1=Double.parseDouble(value);} else if (metric.equals("lamL2")) {this.lamL2=Double.parseDouble(value);} else if (metric.equals("ntrees")) {this.ntrees=Integer.parseInt(value);} else if (metric.equals("sparse_max_features")) {this.sparse_max_features=Integer.parseInt(value);} else if (metric.equals("stepsize")) {this.stepsize=Double.parseDouble(value);} else if (metric.equals("max_nodes")) {this.max_nodes=Integer.parseInt(value);} else if (metric.equals("max_level")) {this.max_level=Integer.parseInt(value);} else if (metric.equals("min_sample")) {this.min_sample=Integer.parseInt(value);} else if (metric.equals("loss")) {this.loss=value;} else if (metric.equals("threads")) {this.threads=Integer.parseInt(value);} else if (metric.equals("new_tree_gain_ratio")) {this.new_tree_gain_ratio=Double.parseDouble(value);} else if (metric.equals("sparse_max_buckets")) {this.sparse_max_buckets=Integer.parseInt(value);} else if (metric.equals("sparse_max_features")) {this.sparse_max_features=Integer.parseInt(value);} else if (metric.equals("sparse_lamL2")) {this.sparse_lamL2=Double.parseDouble(value);} else if (metric.equals("opt")) {this.opt=value;} else if (metric.equals("dense_max_buckets")) {this.dense_max_buckets=Integer.parseInt(value);} else if (metric.equals("min_occurrences")) {this.min_occurrences=Integer.parseInt(value);} else if (metric.equals("copy")) {this.copy=(value.toLowerCase().equals("true")?true:false);} else if (metric.equals("seed")) {this.seed=Integer.parseInt(value);} else if (metric.equals("verbose")) {this.verbose=(value.toLowerCase().equals("true")?true:false) ;} } } } @Override public void set_target(double data []){ if (data==null || data.length<=0){ throw new IllegalStateException(" There is nothing to train on" ); } this.target=data; } @Override public scaler ReturnScaler() { return null; } @Override public void setScaler(scaler sc) { } @Override public void setSeed(int seed) { this.seed=seed;} @Override public int getSeed() { return this.seed;} }
Joejiong/StackNet
src/ml/fastrgf/FRGFClassifier.java
214,062
/* Representation of a Unit Copyright (c) 2003-2014 The Regents of the University of California. All rights reserved. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. PT_COPYRIGHT_VERSION_3 COPYRIGHTENDKEY */ package ptolemy.moml.unit; import java.util.Vector; import ptolemy.data.unit.BaseUnit; import ptolemy.data.unit.UnitUtilities; /////////////////////////////////////////////////////////////////// //// Unit /** Class that contains the internal representation of a Unit. A Unit has the mathematical notation <b>S</b>&lt;E1, E2, ..., En&gt; where <b>S</b> is the <i>scale</i> and &lt;E1, E2, ..., En&gt; is the <i>type</i> of the Unit. <p> This class also contains methods for operating on Units, such as multiply, divide, etc. @author Rowland R Johnson @version $Id$ @since Ptolemy II 8.0 @Pt.ProposedRating Red (rowland) @Pt.AcceptedRating Red (rowland) */ public class Unit implements UnitPresentation { /** Create a Unit with no name and the unitless type. * */ public Unit() { _type = new int[UnitLibrary.getNumCategories()]; for (int i = 0; i < UnitLibrary.getNumCategories(); i++) { _type[i] = 0; } _labels.add("noLabel" + _noLabelCounter++); } /** Create a Unit from a BaseUnit. * @param bu BaseUnit that provides the basis for this Unit. */ public Unit(BaseUnit bu) { this(); String name = bu.getName(); setPrimaryLabel(name); int index = UnitUtilities.getUnitCategoryIndex(name); _type[index] = 1; } /** Create a Unit with a specified name, and the unitless type. * @param name Name of the Unit. */ public Unit(String name) { this(); setPrimaryLabel(name); } /////////////////////////////////////////////////////////////////// //// public methods //// /** Make a copy of this Unit. * @return A new Unit. */ public Unit copy() { Unit retv = new Unit(); retv._setLabels((Vector) getLabels().clone()); int[] newExponents = retv.getType(); for (int i = 0; i < UnitLibrary.getNumCategories(); i++) { newExponents[i] = _type[i]; } retv.setScale(getScale()); return retv; } /** The expression of the Unit that is commonly used by humans. * For example, the unit 4.1868E7&lt;2, 1, -3, 0, 0&gt; will produce the * common expression "calorie second^-1". * @see ptolemy.moml.unit.UnitPresentation#descriptiveForm() */ @Override public String descriptiveForm() { StringBuffer retv = null; Unit unit = UnitLibrary.getUnit(this); if (unit != null) { return unit.getPrimaryLabel(); } UnitExpr factorization = factor(); if (factorization != null) { Vector numerator = new Vector(); Vector denominator = new Vector(); Vector uTerms = factorization.getUTerms(); for (int i = 0; i < uTerms.size(); i++) { UnitTerm uterm = (UnitTerm) uTerms.elementAt(i); if (uterm.getExponent() < 0) { denominator.add(uterm.invert()); } else if (uterm.getExponent() > 0) { numerator.add(uterm); } } if (numerator.size() == 0) { retv = new StringBuffer("1"); } else { retv = new StringBuffer(((UnitTerm) numerator.elementAt(0)) .getUnit().getPrimaryLabel()); for (int i = 1; i < numerator.size(); i++) { retv.append(" " + ((UnitTerm) numerator.elementAt(i)) .getUnit().getPrimaryLabel()); } } if (denominator.size() > 0) { retv.append("/" + ((UnitTerm) denominator.elementAt(0)) .getUnit().getPrimaryLabel()); for (int i = 1; i < denominator.size(); i++) { retv.append(" " + ((UnitTerm) denominator.elementAt(i)) .getUnit().getPrimaryLabel()); } } return retv.toString(); } if (_scale == 1.0) { int numCats = _type.length; StringBuffer desc = new StringBuffer(); for (int i = 0; i < numCats; i++) { if (_type[i] != 0) { Unit baseUnit = UnitLibrary.getBaseUnit(i); // Coverity: getBaseUnit() could return null; if (baseUnit != null) { if (_type[i] == 1) { desc.append(" " + baseUnit.getPrimaryLabel()); } else { desc.append(" " + baseUnit.getPrimaryLabel() + "^" + _type[i]); } } } } return desc.toString().substring(1); } // End up here if nothing works, so just return the formal description return toString(); } /** Divide this Unit by another Unit. * @param divisor The divisor unit. * @return This Unit divided by the divisor. */ public Unit divideBy(Unit divisor) { Unit retv = copy(); int[] otherExponents = divisor.getType(); int[] thisExponents = retv.getType(); for (int i = 0; i < UnitLibrary.getNumCategories(); i++) { thisExponents[i] -= otherExponents[i]; } retv.setType(thisExponents); retv.setScale(retv.getScale() / divisor.getScale()); return retv; } /** Return True if this Unit equals another object * @param object The object to be compared against. * @return True if this Unit equals the other Unit. Return false * if the other object is null or not an instance of Unit. */ @Override public boolean equals(Object object) { if (object == null) { return false; } Unit otherUnit = null; if (!(object instanceof Unit)) { return false; } else { otherUnit = (Unit) object; } int[] otherExponents = otherUnit.getType(); for (int i = 0; i < UnitLibrary.getNumCategories(); i++) { if (_type[i] != otherExponents[i]) { return false; } } if (_scale != otherUnit.getScale()) { return false; } if (!getLabelsString().equals(otherUnit.getLabelsString())) { return false; } return true; } /** Factor a Unit into a UnitExpr that has UnitTerms that are in the * Library. In general, factorization is a <i>lengthy</i> process, and this * method is not a complete factorization algorithm. It only tries some of * the more likely combinations. * @return UnitExpr that is equivalent to to the Unit. */ public UnitExpr factor() { // First see if it is simply an invert Unit invert = UnitLibrary.getUnit(invert()); if (invert != null) { UnitExpr retv = new UnitExpr(); UnitTerm uTerm = new UnitTerm(invert); uTerm.setExponent(-1); retv.addUnitTerm(uTerm); return retv; } // Second see if this is of the form numerator/denominator Vector libraryUnits = UnitLibrary.getLibrary(); for (int i = 0; i < libraryUnits.size(); i++) { Unit factor = (Unit) libraryUnits.elementAt(i); Unit numerator = this.multiplyBy(factor); Unit xx = UnitLibrary.getUnit(numerator); if (xx != null) { UnitExpr retv = new UnitExpr(); if (xx != UnitLibrary.Identity) { UnitTerm uTerm1 = new UnitTerm(xx); retv.addUnitTerm(uTerm1); } UnitTerm uTerm2 = new UnitTerm(factor); uTerm2.setExponent(-1); retv.addUnitTerm(uTerm2); return retv; } } for (int i = 0; i < libraryUnits.size(); i++) { Unit factor = (Unit) libraryUnits.elementAt(i); Unit remainder = this.divideBy(factor); Unit xx = UnitLibrary.getUnit(remainder); if (xx != null && xx != UnitLibrary.Identity) { UnitExpr retv = new UnitExpr(); UnitTerm uTerm = new UnitTerm(factor); retv.addUnitTerm(uTerm); uTerm = new UnitTerm(xx); retv.addUnitTerm(uTerm); return retv; } } return null; } /** Get the labels for a Unit. * @see ptolemy.moml.unit.Unit#getPrimaryLabel() * @return The labels. */ public Vector getLabels() { return _labels; } /** Create a String that is the concatenation of all the labels. * @return The concatenation of the labels. */ public String getLabelsString() { StringBuffer retv = null; if (_labels.size() > 0) { retv = new StringBuffer((String) _labels.elementAt(0)); } else { return ""; } for (int i = 1; i < _labels.size(); i++) { retv.append((String) _labels.elementAt(i) + ","); } return retv.toString(); } /** Get the primary label of a Unit. * A Unit can have more than one label. For example, cm, and centimeter are * labels for the same Unit. There always exists a label that is primary. * @return The primary label. */ public String getPrimaryLabel() { return (String) _labels.elementAt(0); } /** Get the scale. * @return Scale. */ public double getScale() { return _scale; } /** Get the type (represented as a int array) of this Unit. * @return The type (represented as a int array) of this Unit. */ public int[] getType() { return _type; } /** Return a hash code value for this Unit. This method returns * the bitwise xor of the hashCode of the label String, the * categories and the hashCode() of the scale. * @return A hash code value for this Unit. */ @Override public int hashCode() { int hashCode = getLabelsString().hashCode(); for (int i = 0; i < UnitLibrary.getNumCategories(); i++) { hashCode >>>= _type[i]; } hashCode >>>= Double.valueOf(_scale).hashCode(); return hashCode; } /** Return true if the Unit has the same type as another Unit. * @param otherUnit * @return True if the Unit has the same type as the argument. */ public boolean hasSameType(Unit otherUnit) { int[] otherType = otherUnit.getType(); for (int i = 0; i < UnitLibrary.getNumCategories(); i++) { if (_type[i] != otherType[i]) { return false; } } return true; } /** Invert this Unit. * @return The inverse of this Unit. */ public Unit invert() { Unit retv = new Unit(); int[] otherExponents = getType(); int[] exponents = new int[UnitLibrary.getNumCategories()]; for (int i = 0; i < UnitLibrary.getNumCategories(); i++) { exponents[i] = -otherExponents[i]; } retv.setType(exponents); retv.setScale(1.0 / getScale()); return retv; } /** Multiply this Unit by another Unit. * @param multiplicand * @return The product of this Unit multiplied by the argument. */ public Unit multiplyBy(Unit multiplicand) { Unit retv = copy(); int[] otherExponents = multiplicand.getType(); int[] thisExponents = retv.getType(); for (int i = 0; i < UnitLibrary.getNumCategories(); i++) { thisExponents[i] += otherExponents[i]; } retv.setType(thisExponents); retv.setScale(retv.getScale() * multiplicand.getScale()); return retv; } /** Returns of value of this Unit raised to the power of the argument. * @param power The exponent. * @return This Unit raised to the power of the argument. */ public Unit pow(double power) { Unit unit = copy(); int[] exponents = unit.getType(); double scale = unit.getScale(); for (int i = 0; i < UnitLibrary.getNumCategories(); i++) { exponents[i] *= power; } scale = Math.pow(scale, power); unit.setType(exponents); unit.setScale(scale); return unit; } /** Set the primary label. * @param label The primary label. */ public void setPrimaryLabel(String label) { _labels.setElementAt(label, 0); } /** Set the scale. * @param d The scale. */ public void setScale(double d) { _scale = d; } /** Set the type. * @param type */ public void setType(int[] type) { _type = type; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuffer retv = new StringBuffer( "Unit:(" + getLabelsString() + ") " + _scale + "*<" + _type[0]); for (int i = 1; i < UnitLibrary.getNumCategories(); i++) { retv.append(", " + _type[i]); } retv.append(">"); return retv.toString(); } /////////////////////////////////////////////////////////////////// //// protected methods //// /** Set the labels of the Unit. * @param labels The labels. */ protected void _setLabels(Vector labels) { _labels = labels; } /////////////////////////////////////////////////////////////////// //// private variables //// Vector _labels = new Vector(); private static int _noLabelCounter = 0; private double _scale = 1.0; int[] _type; }
erwindl0/ptII
ptolemy/moml/unit/Unit.java
214,063
package org.freehep.util; import java.util.Comparator; /** * * @author Tony Johnson * @version $Id: VersionComparator.java,v 1.3 2008-05-04 12:22:38 murkle Exp $ */ public class VersionComparator implements Comparator { private static String[] special = { "alpha", "beta", "rc" }; private static String pattern = "\\.+"; /** * Compares two version numbers of the form 1.2.3.4 * * @return &gt;0 if v1&gt;v2, &lt;0 if v1&lt;v2 or 0 if v1=v2 */ public int versionNumberCompare(String v1, String v2) throws NumberFormatException { String[] t1 = replaceSpecials(v1).split(pattern); String[] t2 = replaceSpecials(v2).split(pattern); int maxLength = Math.max(t1.length, t2.length); int i = 0; for (; i < maxLength; i++) { int i1 = i < t1.length ? Integer.parseInt(t1[i]) : 0; int i2 = i < t2.length ? Integer.parseInt(t2[i]) : 0; if (i1 == i2) { continue; } return i1 - i2; } return 0; } private static String replaceSpecials(String in) { for (int i = 0; i < special.length; i++) { int j = -special.length + i; in = in.replaceAll(special[i], "." + j + "."); } return in; } @Override public int compare(Object obj, Object obj1) { return versionNumberCompare(obj.toString(), obj1.toString()); } }
mstfelg/geosquared
desktop/src/main/java/org/freehep/util/VersionComparator.java
214,064
package com.baeldung; import org.redisson.api.annotation.REntity; import org.redisson.api.annotation.RId; /** * Created by johnson on 3/9/17. */ @REntity public class LedgerLiveObject { @RId private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
eugenp/tutorials
persistence-modules/redis/src/main/java/com/baeldung/LedgerLiveObject.java
214,065
/** * The MIT License * ------------------------------------------------------------- * Copyright (c) 2008, Rob Ellis, Brock Whitten, Brian Leroux, Joe Bowser, Dave Johnson, Nitobi * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.nitobi.phonegap.api; /** * Each part of the PhoneGap API. * * @author Jose Noheda [[email protected]] * */ public interface Command { /** * Executes the request and returns JS code to chang client state. * * @param instruction the command to execute * @return a string with Javascript code or null */ String execute(String instruction); /** * Determines if this command can process a request. * * @param instruction the command to execute * * @return true if this command understands the petition */ boolean accept(String instruction); }
claymodel/phonegap
blackberry/framework/src/com/nitobi/phonegap/api/Command.java
214,066
/* * Copyright 2023 The original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.morling.onebrc; import sun.misc.Unsafe; import java.io.IOException; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; import java.lang.reflect.Field; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.*; import java.util.stream.IntStream; //Disclaimer: The idea from the segmentation into #core amount of chunks came from previously submitted solutions. public class CalculateAverage_JesseVanRooy { private static final String FILE = "./measurements.txt"; private static final ValueLayout.OfByte DATA_LAYOUT = ValueLayout.JAVA_BYTE; private static final Unsafe UNSAFE = initUnsafe(); private static Unsafe initUnsafe() { try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); return (Unsafe) theUnsafe.get(Unsafe.class); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } } public static class Result { long nameStart; long nameSize; String name; int min; int max; long sum; int count; double min() { return min / 10.0; } double max() { return max / 10.0; } double mean() { return (sum / 10.0) / count; } } public static class ThreadResult { Result[] results; } static final int MAP_SIZE = 16384; static final int MAP_MASK = MAP_SIZE - 1; static final int VALUE_CAPACITY = 10000; static void process(MemorySegment memorySegment, ThreadResult threadResult) { // initialize hash table final int[] keys = new int[MAP_SIZE]; Arrays.fill(keys, -1); final Result[] values = new Result[MAP_SIZE]; // pre-create the result objects final Result[] preCreatedResults = new Result[VALUE_CAPACITY]; int usedPreCreatedResults = 0; for (int i = 0; i < VALUE_CAPACITY; i++) preCreatedResults[i] = new Result(); // load address info final long size = memorySegment.byteSize(); final long address = memorySegment.address(); final long end = address + size; for (long index = address; index < end;) { final long nameStart = index; byte next = UNSAFE.getByte(index); // hash the city name int hash = 0; while (next != ';') { hash = (hash * 33) + next; index++; next = UNSAFE.getByte(index); } final long nameEnd = index; // skip the separator index++; next = UNSAFE.getByte(index); // check for negative boolean negative = next == '-'; if (negative) { index++; next = UNSAFE.getByte(index); } // count the temperature int temperature = next - '0'; index++; next = UNSAFE.getByte(index); if (next != '.') { temperature = (temperature * 10) + (next - '0'); index++; } // skip the . index++; next = UNSAFE.getByte(index); // add the last digit to temperature temperature = (temperature * 10) + (next - '0'); index++; // negate the temperature if needed if (negative) { temperature = -temperature; } // skip the newline index++; // insert into map for (int i = hash; i < hash + MAP_SIZE; i++) { int mapIndex = i & MAP_MASK; if (keys[mapIndex] == -1) { Result result = preCreatedResults[usedPreCreatedResults++]; result.nameStart = nameStart; result.nameSize = nameEnd - nameStart; result.min = temperature; result.max = temperature; result.sum = temperature; result.count = 1; keys[mapIndex] = hash; values[mapIndex] = result; break; } if (keys[mapIndex] == hash) { Result result = values[mapIndex]; result.min = Math.min(result.min, temperature); result.max = Math.max(result.max, temperature); result.sum += temperature; result.count++; break; } } } threadResult.results = Arrays.stream(values).filter(Objects::nonNull).toArray(Result[]::new); for (Result result : threadResult.results) { result.name = new String(memorySegment.asSlice(result.nameStart - address, result.nameSize).toArray(DATA_LAYOUT)); } } public static void main(String[] args) throws IOException, InterruptedException { int numberOfChunks = Runtime.getRuntime().availableProcessors(); try (var fileChannel = FileChannel.open(Path.of(FILE), StandardOpenOption.READ)) { long fileSize = fileChannel.size(); MemorySegment allData = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize, Arena.global()); long segmentSize = (fileSize + numberOfChunks - 1) / numberOfChunks; long[] segmentBounds = new long[numberOfChunks + 1]; segmentBounds[0] = 0; for (int i = 1; i < numberOfChunks; i++) { long chunkAddress = i * segmentSize; while (chunkAddress < fileSize && allData.getAtIndex(DATA_LAYOUT, chunkAddress++) != '\n') { } segmentBounds[i] = Math.min(chunkAddress, fileSize); } segmentBounds[numberOfChunks] = fileSize; ThreadResult[] threadResults = IntStream.range(0, numberOfChunks) .parallel() .mapToObj(i -> { long size = segmentBounds[i + 1] - segmentBounds[i]; long offset = segmentBounds[i]; MemorySegment segment = allData.asSlice(offset, size); ThreadResult result = new ThreadResult(); process(segment, result); return result; }) .toArray(ThreadResult[]::new); HashMap<String, Result> combinedResults = new HashMap<>(1024); for (int i = 0; i < numberOfChunks; i++) { for (Result result : threadResults[i].results) { if (!combinedResults.containsKey(result.name)) { Result newResult = new Result(); newResult.name = result.name; newResult.min = result.min; newResult.max = result.max; newResult.sum = result.sum; newResult.count = result.count; combinedResults.put(result.name, newResult); } else { Result existingResult = combinedResults.get(result.name); existingResult.min = Math.min(existingResult.min, result.min); existingResult.max = Math.max(existingResult.max, result.max); existingResult.sum += result.sum; existingResult.count += result.count; } } } Result[] sortedResults = combinedResults.values().toArray(Result[]::new); Arrays.sort(sortedResults, Comparator.comparing(result -> result.name)); System.out.print("{"); for (int i = 0; i < sortedResults.length; i++) { Result sortedResult = sortedResults[i]; if (i != 0) { System.out.print(", "); } System.out.printf(Locale.US, "%s=%.1f/%.1f/%.1f", sortedResult.name, sortedResult.min(), sortedResult.mean(), sortedResult.max()); } System.out.printf("}\n"); } } }
gunnarmorling/1brc
src/main/java/dev/morling/onebrc/CalculateAverage_JesseVanRooy.java
214,070
/** * Packer version 3.0 (final) * Copyright 2004-2007, Dean Edwards * Web: {@link http://dean.edwards.name/} * * This software is licensed under the MIT license * Web: {@link http://www.opensource.org/licenses/mit-license} * * Ported to Java by Pablo Santiago based on C# version by Jesse Hansen, <twindagger2k @ msn.com> * Web: {@link http://jpacker.googlecode.com/} * Email: <pablo.santiago @ gmail.com> */ package com.jpacker.evaluators; import java.util.regex.Matcher; public class StringEvaluator extends AbstractEvaluator implements Evaluator { private String replacement; public StringEvaluator(String replacement) { this.replacement = replacement; } /** * Replacement function for complicated lookups (e.g. Hello $3 $2) * */ @Override public String evaluate(Matcher matcher, int offset) { int length = getJPattern().getLength(); String result = replacement; while (length-- > 0) { String mg = matcher.group(offset + length); result = result.replace("$" + length, mg == null ? "" : mg); } return result; } }
jindrapetrik/jpexs-decompiler
libsrc/jpacker/src/com/jpacker/evaluators/StringEvaluator.java
214,071
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.common.inject.binder; import org.opensearch.common.annotation.PublicApi; import java.lang.annotation.Annotation; /** * See the EDSL examples at {@link org.opensearch.common.inject.Binder}. * * @author [email protected] (Jesse Wilson) * @since 2.0 * * @opensearch.api */ @PublicApi(since = "1.0.0") public interface AnnotatedElementBuilder { /** * See the EDSL examples at {@link org.opensearch.common.inject.Binder}. */ void annotatedWith(Class<? extends Annotation> annotationType); /** * See the EDSL examples at {@link org.opensearch.common.inject.Binder}. */ void annotatedWith(Annotation annotation); }
opensearch-project/OpenSearch
server/src/main/java/org/opensearch/common/inject/binder/AnnotatedElementBuilder.java
214,072
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package threaddemo.model; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import threaddemo.locking.RWLock; import threaddemo.locking.Locks; /** * A phadhail in which all model methods are locked with a simple monitor. * In this variant, the impl acquires locks automatically, though another * style would be to require the client to do this. * @author Jesse Glick */ final class MonitoredPhadhail extends AbstractPhadhail { private static final class LOCK {} private static final Object LOCK = new LOCK(); private static final RWLock MLOCK = Locks.monitor(LOCK); private static final AbstractPhadhail.Factory FACTORY = new AbstractPhadhail.Factory() { public AbstractPhadhail create(File f) { return new MonitoredPhadhail(f); } }; public static Phadhail create(File f) { return forFile(f, FACTORY); } private MonitoredPhadhail(File f) { super(f); } protected Factory factory() { return FACTORY; } public List<Phadhail> getChildren() { synchronized (LOCK) { return super.getChildren(); } } public String getName() { synchronized (LOCK) { return super.getName(); } } public String getPath() { synchronized (LOCK) { return super.getPath(); } } public boolean hasChildren() { synchronized (LOCK) { return super.hasChildren(); } } public void rename(String nue) throws IOException { synchronized (LOCK) { super.rename(nue); } } public Phadhail createContainerPhadhail(String name) throws IOException { synchronized (LOCK) { return super.createContainerPhadhail(name); } } public Phadhail createLeafPhadhail(String name) throws IOException { synchronized (LOCK) { return super.createLeafPhadhail(name); } } public void delete() throws IOException { synchronized (LOCK) { super.delete(); } } public InputStream getInputStream() throws IOException { synchronized (LOCK) { return super.getInputStream(); } } public OutputStream getOutputStream() throws IOException { synchronized (LOCK) { return super.getOutputStream(); } } public RWLock lock() { return MLOCK; } }
apache/netbeans
java/performance/threaddemo/src/threaddemo/model/MonitoredPhadhail.java
214,075
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan; /** * An application may wish to reference device memory in multiple Vulkan logical devices or instances, in multiple processes, and/or in multiple APIs. This extension enables an application to export non-Vulkan handles from Vulkan memory objects such that the underlying resources can be referenced outside the scope of the Vulkan logical device that created them. * * <h5>Promotion to Vulkan 1.1</h5> * * <p>All functionality in this extension is included in core Vulkan 1.1, with the KHR suffix omitted. The original type, enum and command names are still available as aliases of the core functionality.</p> * * <dl> * <dt><b>Name String</b></dt> * <dd>{@code VK_KHR_external_memory}</dd> * <dt><b>Extension Type</b></dt> * <dd>Device extension</dd> * <dt><b>Registered Extension Number</b></dt> * <dd>73</dd> * <dt><b>Revision</b></dt> * <dd>1</dd> * <dt><b>Extension and Version Dependencies</b></dt> * <dd>{@link KHRExternalMemoryCapabilities VK_KHR_external_memory_capabilities} or <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.1">Version 1.1</a></dd> * <dt><b>Deprecation State</b></dt> * <dd><ul> * <li><em>Promoted</em> to <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.1-promotions">Vulkan 1.1</a></li> * </ul></dd> * <dt><b>Contact</b></dt> * <dd><ul> * <li>James Jones <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_external_memory]%20@cubanismo%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_external_memory%20extension*">cubanismo</a></li> * </ul></dd> * </dl> * * <h5>Other Extension Metadata</h5> * * <dl> * <dt><b>Last Modified Date</b></dt> * <dd>2016-10-20</dd> * <dt><b>IP Status</b></dt> * <dd>No known IP claims.</dd> * <dt><b>Interactions and External Dependencies</b></dt> * <dd><ul> * <li>Interacts with {@link KHRDedicatedAllocation VK_KHR_dedicated_allocation}.</li> * <li>Interacts with {@link NVDedicatedAllocation VK_NV_dedicated_allocation}.</li> * </ul></dd> * <dt><b>Contributors</b></dt> * <dd><ul> * <li>Faith Ekstrand, Intel</li> * <li>Ian Elliott, Google</li> * <li>Jesse Hall, Google</li> * <li>Tobias Hector, Imagination Technologies</li> * <li>James Jones, NVIDIA</li> * <li>Jeff Juliano, NVIDIA</li> * <li>Matthew Netsch, Qualcomm Technologies, Inc.</li> * <li>Daniel Rakos, AMD</li> * <li>Carsten Rohde, NVIDIA</li> * <li>Ray Smith, ARM</li> * <li>Lina Versace, Google</li> * </ul></dd> * </dl> */ public final class KHRExternalMemory { /** The extension specification version. */ public static final int VK_KHR_EXTERNAL_MEMORY_SPEC_VERSION = 1; /** The extension name. */ public static final String VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME = "VK_KHR_external_memory"; /** * Extends {@code VkStructureType}. * * <h5>Enum values:</h5> * * <ul> * <li>{@link #VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR}</li> * <li>{@link #VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR}</li> * <li>{@link #VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR}</li> * </ul> */ public static final int VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR = 1000072000, VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR = 1000072001, VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR = 1000072002; /** Extends {@code VkResult}. */ public static final int VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR = -1000072003; /** VK_QUEUE_FAMILY_EXTERNAL_KHR */ public static final int VK_QUEUE_FAMILY_EXTERNAL_KHR = (~1); private KHRExternalMemory() {} }
LWJGL/lwjgl3
modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/KHRExternalMemory.java
214,076
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.elasticsearch.common.inject; import org.elasticsearch.common.inject.internal.Errors; import org.elasticsearch.common.inject.spi.Element; import org.elasticsearch.common.inject.spi.ElementVisitor; import org.elasticsearch.common.inject.spi.InjectionRequest; import org.elasticsearch.common.inject.spi.MembersInjectorLookup; import org.elasticsearch.common.inject.spi.Message; import org.elasticsearch.common.inject.spi.PrivateElements; import org.elasticsearch.common.inject.spi.ProviderLookup; import org.elasticsearch.common.inject.spi.ScopeBinding; import org.elasticsearch.common.inject.spi.StaticInjectionRequest; import org.elasticsearch.common.inject.spi.TypeConverterBinding; import org.elasticsearch.common.inject.spi.TypeListenerBinding; import java.util.Iterator; import java.util.List; /** * Abstract base class for creating an injector from module elements. * <p> * Extending classes must return {@code true} from any overridden * {@code visit*()} methods, in order for the element processor to remove the * handled element. * * @author [email protected] (Jesse Wilson) */ abstract class AbstractProcessor implements ElementVisitor<Boolean> { protected Errors errors; protected InjectorImpl injector; protected AbstractProcessor(Errors errors) { this.errors = errors; } public void process(Iterable<InjectorShell> isolatedInjectorBuilders) { for (InjectorShell injectorShell : isolatedInjectorBuilders) { process(injectorShell.getInjector(), injectorShell.getElements()); } } public void process(InjectorImpl injector, List<Element> elements) { Errors errorsAnyElement = this.errors; this.injector = injector; try { for (Iterator<Element> i = elements.iterator(); i.hasNext(); ) { Element element = i.next(); this.errors = errorsAnyElement.withSource(element.getSource()); Boolean allDone = element.acceptVisitor(this); if (allDone) { i.remove(); } } } finally { this.errors = errorsAnyElement; this.injector = null; } } @Override public Boolean visit(Message message) { return false; } @Override public Boolean visit(ScopeBinding scopeBinding) { return false; } @Override public Boolean visit(InjectionRequest injectionRequest) { return false; } @Override public Boolean visit(StaticInjectionRequest staticInjectionRequest) { return false; } @Override public Boolean visit(TypeConverterBinding typeConverterBinding) { return false; } @Override public <T> Boolean visit(Binding<T> binding) { return false; } @Override public <T> Boolean visit(ProviderLookup<T> providerLookup) { return false; } @Override public Boolean visit(PrivateElements privateElements) { return false; } @Override public <T> Boolean visit(MembersInjectorLookup<T> lookup) { return false; } @Override public Boolean visit(TypeListenerBinding binding) { return false; } }
crate/crate
libs/guice/src/main/java/org/elasticsearch/common/inject/AbstractProcessor.java
214,077
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.elasticsearch.common.inject.internal; import org.elasticsearch.common.inject.Binder; import org.elasticsearch.common.inject.Key; import org.elasticsearch.common.inject.spi.Element; import org.elasticsearch.common.inject.spi.InstanceBinding; import java.util.List; /** * Bind a value or constant. * * @author [email protected] (Jesse Wilson) */ public abstract class AbstractBindingBuilder<T> { public static final String IMPLEMENTATION_ALREADY_SET = "Implementation is set more than once."; public static final String SINGLE_INSTANCE_AND_SCOPE = "Setting the scope is not permitted when binding to a single instance."; public static final String SCOPE_ALREADY_SET = "Scope is set more than once."; public static final String BINDING_TO_NULL = "Binding to null instances is not allowed. " + "Use toProvider(Providers.of(null)) if this is your intended behaviour."; protected final List<Element> elements; protected final int position; protected final Binder binder; private BindingImpl<T> binding; public AbstractBindingBuilder(Binder binder, List<Element> elements, Object source, Key<T> key) { this.binder = binder; this.elements = elements; this.position = elements.size(); this.binding = new UntargettedBindingImpl<>(source, key, Scoping.UNSCOPED); elements.add(position, this.binding); } protected BindingImpl<T> getBinding() { return binding; } protected BindingImpl<T> setBinding(BindingImpl<T> binding) { this.binding = binding; elements.set(position, binding); return binding; } public void asEagerSingleton() { checkNotScoped(); setBinding(getBinding().withEagerSingletonScoping()); } protected void checkNotTargetted() { if ((binding instanceof UntargettedBindingImpl) == false) { binder.addError(IMPLEMENTATION_ALREADY_SET); } } protected void checkNotScoped() { // Scoping isn't allowed when we have only one instance. if (binding instanceof InstanceBinding) { binder.addError(SINGLE_INSTANCE_AND_SCOPE); return; } if (binding.getScoping().isExplicitlyScoped()) { binder.addError(SCOPE_ALREADY_SET); } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/inject/internal/AbstractBindingBuilder.java
214,078
package com.morihacky.android.rxjava.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import com.morihacky.android.rxjava.R; import com.morihacky.android.rxjava.retrofit.Contributor; import com.morihacky.android.rxjava.retrofit.GithubApi; import com.morihacky.android.rxjava.retrofit.GithubService; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; import timber.log.Timber; public class PseudoCacheMergeFragment extends BaseFragment { @BindView(R.id.log_list) ListView _resultList; private ArrayAdapter<String> _adapter; private HashMap<String, Long> _contributionMap = null; private HashMap<Contributor, Long> _resultAgeMap = new HashMap<>(); private Unbinder unbinder; @Override public View onCreateView( LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.fragment_pseudo_cache_concat, container, false); unbinder = ButterKnife.bind(this, layout); _initializeCache(); return layout; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @OnClick(R.id.btn_start_pseudo_cache) public void onDemoPseudoCacheClicked() { _adapter = new ArrayAdapter<>(getActivity(), R.layout.item_log, R.id.item_log, new ArrayList<>()); _resultList.setAdapter(_adapter); _initializeCache(); Observable.merge(_getCachedData(), _getFreshData()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( new DisposableObserver<Pair<Contributor, Long>>() { @Override public void onComplete() { Timber.d("done loading all data"); } @Override public void onError(Throwable e) { Timber.e(e, "arr something went wrong"); } @Override public void onNext(Pair<Contributor, Long> contributorAgePair) { Contributor contributor = contributorAgePair.first; if (_resultAgeMap.containsKey(contributor) && _resultAgeMap.get(contributor) > contributorAgePair.second) { return; } _contributionMap.put(contributor.login, contributor.contributions); _resultAgeMap.put(contributor, contributorAgePair.second); _adapter.clear(); _adapter.addAll(getListStringFromMap()); } }); } private List<String> getListStringFromMap() { List<String> list = new ArrayList<>(); for (String username : _contributionMap.keySet()) { String rowLog = String.format("%s [%d]", username, _contributionMap.get(username)); list.add(rowLog); } return list; } private Observable<Pair<Contributor, Long>> _getCachedData() { List<Pair<Contributor, Long>> list = new ArrayList<>(); Pair<Contributor, Long> dataWithAgePair; for (String username : _contributionMap.keySet()) { Contributor c = new Contributor(); c.login = username; c.contributions = _contributionMap.get(username); dataWithAgePair = new Pair<>(c, System.currentTimeMillis()); list.add(dataWithAgePair); } return Observable.fromIterable(list); } private Observable<Pair<Contributor, Long>> _getFreshData() { String githubToken = getResources().getString(R.string.github_oauth_token); GithubApi githubService = GithubService.createGithubService(githubToken); return githubService .contributors("square", "retrofit") .flatMap(Observable::fromIterable) .map(contributor -> new Pair<>(contributor, System.currentTimeMillis())); } private void _initializeCache() { _contributionMap = new HashMap<>(); _contributionMap.put("JakeWharton", 0l); _contributionMap.put("pforhan", 0l); _contributionMap.put("edenman", 0l); _contributionMap.put("swankjesse", 0l); _contributionMap.put("bruceLee", 0l); } }
kaushikgopal/RxJava-Android-Samples
app/src/main/java/com/morihacky/android/rxjava/fragments/PseudoCacheMergeFragment.java
214,079
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.SortedMap; import java.util.SortedSet; import java.util.concurrent.atomic.AtomicInteger; /** * A comparator with added methods to support common functions. For example: * <pre> {@code * * if (Ordering.from(comparator).reverse().isOrdered(list)) { ... }}</pre> * * <p>The {@link #from(Comparator)} method returns the equivalent {@code * Ordering} instance for a pre-existing comparator. You can also skip the * comparator step and extend {@code Ordering} directly: <pre> {@code * * Ordering<String> byLengthOrdering = new Ordering<String>() { * public int compare(String left, String right) { * return Ints.compare(left.length(), right.length()); * } * };}</pre> * * Except as noted, the orderings returned by the factory methods of this * class are serializable if and only if the provided instances that back them * are. For example, if {@code ordering} and {@code function} can themselves be * serialized, then {@code ordering.onResultOf(function)} can as well. * * @author Jesse Wilson * @author Kevin Bourrillion * @since 2010.01.04 <b>stable</b> (imported from Google Collections Library) */ @GwtCompatible public abstract class Ordering<T> implements Comparator<T> { // Static factories /** * Returns a serializable ordering that uses the natural order of the values. * The ordering throws a {@link NullPointerException} when passed a null * parameter. * * <p>The type specification is {@code <C extends Comparable>}, instead of * the technically correct {@code <C extends Comparable<? super C>>}, to * support legacy types from before Java 5. */ @GwtCompatible(serializable = true) @SuppressWarnings("unchecked") // TODO: the right way to explain this?? public static <C extends Comparable> Ordering<C> natural() { return (Ordering) NaturalOrdering.INSTANCE; } /** * Returns an ordering for a pre-existing {@code comparator}. Note * that if the comparator is not pre-existing, and you don't require * serialization, you can subclass {@code Ordering} and implement its * {@link #compare(Object, Object) compare} method instead. * * @param comparator the comparator that defines the order */ @GwtCompatible(serializable = true) public static <T> Ordering<T> from(Comparator<T> comparator) { return (comparator instanceof Ordering) ? (Ordering<T>) comparator : new ComparatorOrdering<T>(comparator); } /** * Simply returns its argument. * * @deprecated no need to use this */ @GwtCompatible(serializable = true) @Deprecated public static <T> Ordering<T> from(Ordering<T> ordering) { return checkNotNull(ordering); } /** * Returns an ordering that compares objects according to the order in * which they appear in the given list. Only objects present in the list * (according to {@link Object#equals}) may be compared. This comparator * imposes a "partial ordering" over the type {@code T}. Subsequent changes * to the {@code valuesInOrder} list will have no effect on the returned * comparator. Null values in the list are not supported. * * <p>The returned comparator throws an {@link ClassCastException} when it * receives an input parameter that isn't among the provided values. * * <p>The generated comparator is serializable if all the provided values are * serializable. * * @param valuesInOrder the values that the returned comparator will be able * to compare, in the order the comparator should induce * @return the comparator described above * @throws NullPointerException if any of the provided values is null * @throws IllegalArgumentException if {@code valuesInOrder} contains any * duplicate values (according to {@link Object#equals}) */ @GwtCompatible(serializable = true) public static <T> Ordering<T> explicit(List<T> valuesInOrder) { return new ExplicitOrdering<T>(valuesInOrder); } /** * Returns an ordering that compares objects according to the order in * which they are given to this method. Only objects present in the argument * list (according to {@link Object#equals}) may be compared. This comparator * imposes a "partial ordering" over the type {@code T}. Null values in the * argument list are not supported. * * <p>The returned comparator throws a {@link ClassCastException} when it * receives an input parameter that isn't among the provided values. * * <p>The generated comparator is serializable if all the provided values are * serializable. * * @param leastValue the value which the returned comparator should consider * the "least" of all values * @param remainingValuesInOrder the rest of the values that the returned * comparator will be able to compare, in the order the comparator should * follow * @return the comparator described above * @throws NullPointerException if any of the provided values is null * @throws IllegalArgumentException if any duplicate values (according to * {@link Object#equals(Object)}) are present among the method arguments */ @GwtCompatible(serializable = true) public static <T> Ordering<T> explicit( T leastValue, T... remainingValuesInOrder) { return explicit(Lists.asList(leastValue, remainingValuesInOrder)); } /** * Exception thrown by a {@link Ordering#explicit(List)} or {@link * Ordering#explicit(Object, Object[])} comparator when comparing a value * outside the set of values it can compare. Extending {@link * ClassCastException} may seem odd, but it is required. */ // TODO: consider making this exception type public. or consider getting rid // of it. @VisibleForTesting static class IncomparableValueException extends ClassCastException { final Object value; IncomparableValueException(Object value) { super("Cannot compare value: " + value); this.value = value; } private static final long serialVersionUID = 0; } /** * Returns an arbitrary ordering over all objects, for which {@code compare(a, * b) == 0} implies {@code a == b} (identity equality). There is no meaning * whatsoever to the order imposed, but it is constant for the life of the VM. * * <p>Because the ordering is identity-based, it is not "consistent with * {@link Object#equals(Object)}" as defined by {@link Comparator}. Use * caution when building a {@link SortedSet} or {@link SortedMap} from it, as * the resulting collection will not behave exactly according to spec. * * <p>This ordering is not serializable, as its implementation relies on * {@link System#identityHashCode(Object)}, so its behavior cannot be * preserved across serialization. * * @since 2010.01.04 <b>tentative</b> */ public static Ordering<Object> arbitrary() { return ArbitraryOrderingHolder.ARBITRARY_ORDERING; } private static class ArbitraryOrderingHolder { static final Ordering<Object> ARBITRARY_ORDERING = new ArbitraryOrdering(); } @VisibleForTesting static class ArbitraryOrdering extends Ordering<Object> { private Map<Object, Integer> uids = Platform.tryWeakKeys(new MapMaker()).makeComputingMap( new Function<Object, Integer>() { final AtomicInteger counter = new AtomicInteger(0); public Integer apply(Object from) { return counter.getAndIncrement(); } }); /*@Override*/ public int compare(Object left, Object right) { if (left == right) { return 0; } int leftCode = identityHashCode(left); int rightCode = identityHashCode(right); if (leftCode != rightCode) { return leftCode < rightCode ? -1 : 1; } // identityHashCode collision (rare, but not as rare as you'd think) int result = uids.get(left).compareTo(uids.get(right)); if (result == 0) { throw new AssertionError(); // extremely, extremely unlikely. } return result; } @Override public String toString() { return "Ordering.arbitrary()"; } /* * We need to be able to mock identityHashCode() calls for tests, because it * can take 1-10 seconds to find colliding objects. Mocking frameworks that * can do magic to mock static method calls still can't do so for a system * class, so we need the indirection. In production, Hotspot should still * recognize that the call is 1-morphic and should still be willing to * inline it if necessary. */ int identityHashCode(Object object) { return System.identityHashCode(object); } } /** * Returns an ordering that compares objects by the natural ordering of their * string representations as returned by {@code toString()}. It does not * support null values. * * <p>The comparator is serializable. */ @GwtCompatible(serializable = true) public static Ordering<Object> usingToString() { return UsingToStringOrdering.INSTANCE; } /** * Returns an ordering which tries each given comparator in order until a * non-zero result is found, returning that result, and returning zero only if * all comparators return zero. The returned ordering is based on the state of * the {@code comparators} iterable at the time it was provided to this * method. * * <p>The returned ordering is equivalent to that produced using {@code * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}. * * <p><b>Warning:</b> Supplying an argument with undefined iteration order, * such as a {@link HashSet}, will produce non-deterministic results. * * @param comparators the comparators to try in order */ @GwtCompatible(serializable = true) public static <T> Ordering<T> compound( Iterable<? extends Comparator<? super T>> comparators) { return new CompoundOrdering<T>(comparators); } /** * Constructs a new instance of this class (only invokable by the subclass * constructor, typically implicit). */ protected Ordering() {} // Non-static factories /** * Returns an ordering which first uses the ordering {@code this}, but which * in the event of a "tie", then delegates to {@code secondaryComparator}. * For example, to sort a bug list first by status and second by priority, you * might use {@code byStatus.compound(byPriority)}. For a compound ordering * with three or more components, simply chain multiple calls to this method. * * <p>An ordering produced by this method, or a chain of calls to this method, * is equivalent to one created using {@link Ordering#compound(Iterable)} on * the same component comparators. */ @GwtCompatible(serializable = true) public <U extends T> Ordering<U> compound( Comparator<? super U> secondaryComparator) { return new CompoundOrdering<U>(this, checkNotNull(secondaryComparator)); } /** * Returns the reverse of this ordering; the {@code Ordering} equivalent to * {@link Collections#reverseOrder(Comparator)}. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().reverse(); @GwtCompatible(serializable = true) public <S extends T> Ordering<S> reverse() { return new ReverseOrdering<S>(this); } /** * Returns a new ordering on {@code F} which orders elements by first applying * a function to them, then comparing those results using {@code this}. For * example, to compare objects by their string forms, in a case-insensitive * manner, use: <pre> {@code * * Ordering.from(String.CASE_INSENSITIVE_ORDER) * .onResultOf(Functions.toStringFunction())}</pre> */ @GwtCompatible(serializable = true) public <F> Ordering<F> onResultOf(Function<F, ? extends T> function) { return new ByFunctionOrdering<F, T>(function, this); } /** * Returns a new ordering which sorts iterables by comparing corresponding * elements pairwise until a nonzero result is found; imposes "dictionary * order". If the end of one iterable is reached, but not the other, the * shorter iterable is considered to be less than the longer one. For example, * a lexicographical natural ordering over integers considers {@code * [] < [1] < [1, 1] < [1, 2] < [2]}. * * <p>Note that {@code ordering.lexicographical().reverse()} is not * equivalent to {@code ordering.reverse().lexicographical()} (consider how * each would order {@code [1]} and {@code [1, 1]}). * * @since 2010.01.04 <b>tentative</b> */ @GwtCompatible(serializable = true) // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<Iterable<String>> o = // Ordering.<String>natural().lexicographical(); public <S extends T> Ordering<Iterable<S>> lexicographical() { /* * Note that technically the returned ordering should be capable of * handling not just {@code Iterable<S>} instances, but also any {@code * Iterable<? extends S>}. However, the need for this comes up so rarely * that it doesn't justify making everyone else deal with the very ugly * wildcard. */ return new LexicographicalOrdering<S>(this); } /** * Returns an ordering that treats {@code null} as less than all other values * and uses {@code this} to compare non-null values. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().nullsFirst(); @GwtCompatible(serializable = true) public <S extends T> Ordering<S> nullsFirst() { return new NullsFirstOrdering<S>(this); } /** * Returns an ordering that treats {@code null} as greater than all other * values and uses this ordering to compare non-null values. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().nullsLast(); @GwtCompatible(serializable = true) public <S extends T> Ordering<S> nullsLast() { return new NullsLastOrdering<S>(this); } /** * {@link Collections#binarySearch(List, Object, Comparator) Searches} * {@code sortedList} for {@code key} using the binary search algorithm. The * list must be sorted using this ordering. * * @param sortedList the list to be searched * @param key the key to be searched for */ public int binarySearch(List<? extends T> sortedList, T key) { return Collections.binarySearch(sortedList, key, this); } /** * Returns a copy of the given iterable sorted by this ordering. The input is * not modified. The returned list is modifiable, serializable, and has random * access. * * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not collapse * elements that compare as zero, and the resulting collection does not * maintain its own sort order. * * @param iterable the elements to be copied and sorted * @return a new list containing the given elements in sorted order */ public <E extends T> List<E> sortedCopy(Iterable<E> iterable) { List<E> list = Lists.newArrayList(iterable); Collections.sort(list, this); return list; } /** * Returns {@code true} if each element in {@code iterable} after the first is * greater than or equal to the element that preceded it, according to this * ordering. Note that this is always true when the iterable has fewer than * two elements. */ public boolean isOrdered(Iterable<? extends T> iterable) { Iterator<? extends T> it = iterable.iterator(); if (it.hasNext()) { T prev = it.next(); while (it.hasNext()) { T next = it.next(); if (compare(prev, next) > 0) { return false; } prev = next; } } return true; } /** * Returns {@code true} if each element in {@code iterable} after the first is * <i>strictly</i> greater than the element that preceded it, according to * this ordering. Note that this is always true when the iterable has fewer * than two elements. */ public boolean isStrictlyOrdered(Iterable<? extends T> iterable) { Iterator<? extends T> it = iterable.iterator(); if (it.hasNext()) { T prev = it.next(); while (it.hasNext()) { T next = it.next(); if (compare(prev, next) >= 0) { return false; } prev = next; } } return true; } /** * Returns the largest of the specified values according to this ordering. If * there are multiple largest values, the first of those is returned. * * @param iterable the iterable whose maximum element is to be determined * @throws NoSuchElementException if {@code iterable} is empty * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E max(Iterable<E> iterable) { Iterator<E> iterator = iterable.iterator(); // let this throw NoSuchElementException as necessary E maxSoFar = iterator.next(); while (iterator.hasNext()) { maxSoFar = max(maxSoFar, iterator.next()); } return maxSoFar; } /** * Returns the largest of the specified values according to this ordering. If * there are multiple largest values, the first of those is returned. * * @param a value to compare, returned if greater than or equal to the rest. * @param b value to compare * @param c value to compare * @param rest values to compare * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E max(E a, E b, E c, E... rest) { E maxSoFar = max(max(a, b), c); for (E r : rest) { maxSoFar = max(maxSoFar, r); } return maxSoFar; } /** * Returns the larger of the two values according to this ordering. If the * values compare as 0, the first is returned. * * <p><b>Implementation note:</b> this method is invoked by the default * implementations of the other {@code max} overloads, so overriding it will * affect their behavior. * * @param a value to compare, returned if greater than or equal to b. * @param b value to compare. * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E max(E a, E b) { return compare(a, b) >= 0 ? a : b; } /** * Returns the smallest of the specified values according to this ordering. If * there are multiple smallest values, the first of those is returned. * * @param iterable the iterable whose minimum element is to be determined * @throws NoSuchElementException if {@code iterable} is empty * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E min(Iterable<E> iterable) { Iterator<E> iterator = iterable.iterator(); // let this throw NoSuchElementException as necessary E minSoFar = iterator.next(); while (iterator.hasNext()) { minSoFar = min(minSoFar, iterator.next()); } return minSoFar; } /** * Returns the smallest of the specified values according to this ordering. If * there are multiple smallest values, the first of those is returned. * * @param a value to compare, returned if less than or equal to the rest. * @param b value to compare * @param c value to compare * @param rest values to compare * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E min(E a, E b, E c, E... rest) { E minSoFar = min(min(a, b), c); for (E r : rest) { minSoFar = min(minSoFar, r); } return minSoFar; } /** * Returns the smaller of the two values according to this ordering. If the * values compare as 0, the first is returned. * * <p><b>Implementation note:</b> this method is invoked by the default * implementations of the other {@code min} overloads, so overriding it will * affect their behavior. * * @param a value to compare, returned if less than or equal to b. * @param b value to compare. * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E min(E a, E b) { return compare(a, b) <= 0 ? a : b; } // Never make these public static final int LEFT_IS_GREATER = 1; static final int RIGHT_IS_GREATER = -1; }
codemasta/XobotOS
android/upstream/com/google/common/collect/Ordering.java
214,080
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package threaddemo.views.looktree; import javax.swing.tree.TreePath; /** * Path from root to a lower "bottom" node in the look tree. * @author Jesse Glick */ public final class LookTreePath extends TreePath { private final LookTreeNode bottom; public LookTreePath(LookTreeNode node) { bottom = node; } public Object[] getPath() { int c = getPathCount(); Object[] path = new Object[c]; LookTreeNode n = bottom; for (int i = c - 1; i >= 0; i--) { path[i] = n; n = n.getParent(); } return path; } public int getPathCount() { LookTreeNode n = bottom; int i = 0; while (n != null) { i++; n = n.getParent(); } return i; } public Object getPathComponent(int x) { int c = getPathCount(); LookTreeNode n = bottom; for (int i = 0; i < c - x - 1; i++) { n = n.getParent(); } return n; } public TreePath pathByAddingChild(Object child) { return new LookTreePath((LookTreeNode)child); } public boolean equals(Object o) { return (o instanceof LookTreePath) && ((LookTreePath)o).bottom == bottom; } public int hashCode() { return bottom.hashCode(); } public Object getLastPathComponent() { return bottom; } public TreePath getParentPath() { LookTreeNode p = bottom.getParent(); if (p != null) { return new LookTreePath(p); } else { return null; } } }
apache/netbeans
java/performance/threaddemo/src/threaddemo/views/looktree/LookTreePath.java
214,081
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.docx4j.com.google.common.collect; import org.checkerframework.checker.nullness.qual.Nullable; import org.docx4j.com.google.common.annotations.GwtCompatible; import org.docx4j.com.google.common.primitives.Ints; /** * Static methods for implementing hash-based collections. * * @author Kevin Bourrillion * @author Jesse Wilson * @author Austin Appleby */ @GwtCompatible final class Hashing { private Hashing() {} /* * These should be ints, but we need to use longs to force GWT to do the multiplications with * enough precision. */ private static final long C1 = 0xcc9e2d51; private static final long C2 = 0x1b873593; /* * This method was rewritten in Java from an intermediate step of the Murmur hash function in * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which contained the * following header: * * MurmurHash3 was written by Austin Appleby, and is placed in the public domain. The author * hereby disclaims copyright to this source code. */ static int smear(int hashCode) { return (int) (C2 * Integer.rotateLeft((int) (hashCode * C1), 15)); } static int smearedHash(@Nullable Object o) { return smear((o == null) ? 0 : o.hashCode()); } private static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; static int closedTableSize(int expectedEntries, double loadFactor) { // Get the recommended table size. // Round down to the nearest power of 2. expectedEntries = Math.max(expectedEntries, 2); int tableSize = Integer.highestOneBit(expectedEntries); // Check to make sure that we will not exceed the maximum load factor. if (expectedEntries > (int) (loadFactor * tableSize)) { tableSize <<= 1; return (tableSize > 0) ? tableSize : MAX_TABLE_SIZE; } return tableSize; } static boolean needsResizing(int size, int tableSize, double loadFactor) { return size > loadFactor * tableSize && tableSize < MAX_TABLE_SIZE; } }
plutext/docx4j
docx4j-core/src/main/java/org/docx4j/com/google/common/collect/Hashing.java
214,082
/* * Copyright (C) 2001-2016 Food and Agriculture Organization of the * United Nations (FAO-UN), United Nations World Food Programme (WFP) * and United Nations Environment Programme (UNEP) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, * Rome - Italy. email: [email protected] */ package org.fao.geonet.kernel; import org.fao.geonet.constants.Geonet; import org.fao.geonet.utils.Log; import org.fao.geonet.utils.Xml; import org.jdom.Element; import org.jdom.JDOMException; import java.io.IOException; /** * A simple container class for some add methods in {@link EditLib} Created by Jesse on 12/10/13. */ public class AddElemValue { private final String stringValue; private final Element nodeValue; public AddElemValue(String stringValue) throws JDOMException, IOException { Element finalNodeVal = null; String finalStringVal = stringValue.replaceAll("</?gn_(add|replace|delete)>", ""); if (Xml.isXMLLike(finalStringVal)) { try { finalNodeVal = Xml.loadString(stringValue, false); finalStringVal = null; } catch (JDOMException e) { Log.debug(Geonet.EDITORADDELEMENT, "Invalid XML fragment to insert " + stringValue + ". Error is: " + e.getMessage(), e); throw e; } catch (IOException e) { Log.error(Geonet.EDITORADDELEMENT, "Error with XML fragment to insert " + stringValue + ". Error is: " + e.getMessage(), e); throw e; } } this.nodeValue = finalNodeVal; this.stringValue = finalStringVal; } public AddElemValue(Element nodeValue) { this.nodeValue = nodeValue; this.stringValue = null; } public boolean isXml() { return nodeValue != null; } public String getStringValue() { return stringValue; } public Element getNodeValue() { return nodeValue; } }
IZRK/core-geonetwork
core/src/main/java/org/fao/geonet/kernel/AddElemValue.java
214,083
/** * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject.spi; import java.util.Set; /** * Implemented by {@link com.google.inject.Binding bindings}, {@link com.google.inject.Provider * providers} and instances that expose their dependencies explicitly. * * @author [email protected] (Jesse Wilson) * @since 2.0 */ public interface HasDependencies { /** * Returns the known dependencies for this type. If this has dependencies whose values are not * known statically, a dependency for the {@link com.google.inject.Injector Injector} will be * included in the returned set. * * @return a possibly empty set */ Set<Dependency<?>> getDependencies(); }
ckashby/roboguice
guice/core/src/com/google/inject/spi/HasDependencies.java
214,084
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject.spi; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.collect.ImmutableSet; import com.google.inject.Binder; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.internal.Errors; import com.google.inject.util.Types; import java.util.Set; /** * A lookup of the provider for a type. Lookups are created explicitly in a module using {@link * com.google.inject.Binder#getProvider(Class) getProvider()} statements: * * <pre> * Provider&lt;PaymentService&gt; paymentServiceProvider * = getProvider(PaymentService.class);</pre> * * @author [email protected] (Jesse Wilson) * @since 2.0 */ public final class ProviderLookup<T> implements Element { private final Object source; private final Dependency<T> dependency; private Provider<T> delegate; public ProviderLookup(Object source, Key<T> key) { this(source, Dependency.get(checkNotNull(key, "key"))); } /** @since 4.0 */ public ProviderLookup(Object source, Dependency<T> dependency) { this.source = checkNotNull(source, "source"); this.dependency = checkNotNull(dependency, "dependency"); } @Override public Object getSource() { return source; } public Key<T> getKey() { return dependency.getKey(); } /** @since 4.0 */ public Dependency<T> getDependency() { return dependency; } @Override public <T> T acceptVisitor(ElementVisitor<T> visitor) { return visitor.visit(this); } /** * Sets the actual provider. * * @throws IllegalStateException if the delegate is already set */ public void initializeDelegate(Provider<T> delegate) { checkState(this.delegate == null, "delegate already initialized"); this.delegate = checkNotNull(delegate, "delegate"); } @Override public void applyTo(Binder binder) { initializeDelegate(binder.withSource(getSource()).getProvider(dependency)); } /** * Returns the delegate provider, or {@code null} if it has not yet been initialized. The delegate * will be initialized when this element is processed, or otherwise used to create an injector. */ public Provider<T> getDelegate() { return delegate; } /** * Returns the looked up provider. The result is not valid until this lookup has been initialized, * which usually happens when the injector is created. The provider will throw an {@code * IllegalStateException} if you try to use it beforehand. */ public Provider<T> getProvider() { return new ProviderWithDependencies<T>() { @Override public T get() { Provider<T> local = delegate; if (local == null) { throw new IllegalStateException( "This Provider cannot be used until the Injector has been created."); } return local.get(); } @Override public Set<Dependency<?>> getDependencies() { // We depend on Provider<T>, not T directly. This is an important distinction // for dependency analysis tools that short-circuit on providers. Key<?> providerKey = getKey().ofType(Types.providerOf(getKey().getTypeLiteral().getType())); return ImmutableSet.<Dependency<?>>of(Dependency.get(providerKey)); } @Override public String toString() { return "Provider<" + getKey().getTypeLiteral() + ">"; } }; } @Override public String toString() { return MoreObjects.toStringHelper(ProviderLookup.class) .add("dependency", dependency) .add("source", Errors.convert(source)) .toString(); } @Override public boolean equals(Object obj) { return obj instanceof ProviderLookup && ((ProviderLookup<?>) obj).dependency.equals(dependency) && ((ProviderLookup<?>) obj).source.equals(source); } @Override public int hashCode() { return Objects.hashCode(dependency, source); } }
google/guice
core/src/com/google/inject/spi/ProviderLookup.java
214,085
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.metrics; import com.google.caliper.BeforeExperiment; import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Field; /** * Caliper based micro benchmarks for Gson * * @author Inderjeet Singh * @author Jesse Wilson * @author Joel Leitch */ public class BagOfPrimitivesDeserializationBenchmark { private Gson gson; private String json; public static void main(String[] args) { NonUploadingCaliperRunner.run(BagOfPrimitivesDeserializationBenchmark.class, args); } @BeforeExperiment void setUp() throws Exception { this.gson = new Gson(); BagOfPrimitives bag = new BagOfPrimitives(10L, 1, false, "foo"); this.json = gson.toJson(bag); } /** Benchmark to measure Gson performance for deserializing an object */ public void timeBagOfPrimitivesDefault(int reps) { for (int i = 0; i < reps; ++i) { gson.fromJson(json, BagOfPrimitives.class); } } /** Benchmark to measure deserializing objects by hand */ public void timeBagOfPrimitivesStreaming(int reps) throws IOException { for (int i = 0; i < reps; ++i) { StringReader reader = new StringReader(json); JsonReader jr = new JsonReader(reader); jr.beginObject(); long longValue = 0; int intValue = 0; boolean booleanValue = false; String stringValue = null; while (jr.hasNext()) { String name = jr.nextName(); if (name.equals("longValue")) { longValue = jr.nextLong(); } else if (name.equals("intValue")) { intValue = jr.nextInt(); } else if (name.equals("booleanValue")) { booleanValue = jr.nextBoolean(); } else if (name.equals("stringValue")) { stringValue = jr.nextString(); } else { throw new IOException("Unexpected name: " + name); } } jr.endObject(); new BagOfPrimitives(longValue, intValue, booleanValue, stringValue); } } /** * This benchmark measures the ideal Gson performance: the cost of parsing a JSON stream and * setting object values by reflection. We should strive to reduce the discrepancy between this * and {@link #timeBagOfPrimitivesDefault(int)} . */ public void timeBagOfPrimitivesReflectionStreaming(int reps) throws Exception { for (int i = 0; i < reps; ++i) { StringReader reader = new StringReader(json); JsonReader jr = new JsonReader(reader); jr.beginObject(); BagOfPrimitives bag = new BagOfPrimitives(); while (jr.hasNext()) { String name = jr.nextName(); for (Field field : BagOfPrimitives.class.getDeclaredFields()) { if (field.getName().equals(name)) { Class<?> fieldType = field.getType(); if (fieldType.equals(long.class)) { field.setLong(bag, jr.nextLong()); } else if (fieldType.equals(int.class)) { field.setInt(bag, jr.nextInt()); } else if (fieldType.equals(boolean.class)) { field.setBoolean(bag, jr.nextBoolean()); } else if (fieldType.equals(String.class)) { field.set(bag, jr.nextString()); } else { throw new RuntimeException("Unexpected: type: " + fieldType + ", name: " + name); } } } } jr.endObject(); } } }
Marcono1234/gson
metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java
214,086
/* * The MIT License * * Copyright 2014 Jesse Glick. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jenkins.model; import static java.util.logging.Level.FINE; import static java.util.logging.Level.FINER; import static java.util.logging.Level.INFO; import static java.util.logging.Level.WARNING; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Util; import hudson.model.Job; import hudson.model.Run; import hudson.util.AtomicFileWriter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Converts legacy {@code builds} directories to the current format. * * There would be one instance associated with each {@link Job}, to retain ID → build# mapping. * * The {@link Job#getBuildDir} is passed to every method call (rather than being cached) in case it is moved. */ @Restricted(NoExternalUse.class) public final class RunIdMigrator { private final DateFormat legacyIdFormatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); static final Logger LOGGER = Logger.getLogger(RunIdMigrator.class.getName()); private static final String MAP_FILE = "legacyIds"; /** avoids wasting a map for new jobs */ private static final Map<String, Integer> EMPTY = new TreeMap<>(); private @NonNull Map<String, Integer> idToNumber = EMPTY; public RunIdMigrator() {} /** * @return whether there was a file to load */ private boolean load(File dir) { File f = new File(dir, MAP_FILE); if (!f.isFile()) { return false; } if (f.length() == 0) { return true; } idToNumber = new TreeMap<>(); try { for (String line : Files.readAllLines(Util.fileToPath(f), StandardCharsets.UTF_8)) { int i = line.indexOf(' '); idToNumber.put(line.substring(0, i), Integer.parseInt(line.substring(i + 1))); } } catch (Exception x) { // IOException, IndexOutOfBoundsException, NumberFormatException LOGGER.log(WARNING, "could not read from " + f, x); } return true; } private void save(File dir) { File f = new File(dir, MAP_FILE); try (AtomicFileWriter w = new AtomicFileWriter(f)) { try { synchronized (this) { for (Map.Entry<String, Integer> entry : idToNumber.entrySet()) { w.write(entry.getKey() + ' ' + entry.getValue() + '\n'); } } w.commit(); } finally { w.abort(); } } catch (IOException x) { LOGGER.log(WARNING, "could not save changes to " + f, x); } } /** * Called when a job is first created. * Just saves an empty marker indicating that this job needs no migration. * @param dir as in {@link Job#getBuildDir} */ public void created(File dir) { save(dir); } /** * Perform one-time migration if this has not been done already. * Where previously there would be a {@code 2014-01-02_03-04-05/build.xml} specifying {@code <number>99</number>} plus a symlink {@code 99 → 2014-01-02_03-04-05}, * after migration there will be just {@code 99/build.xml} specifying {@code <id>2014-01-02_03-04-05</id>} and {@code <timestamp>…</timestamp>} according to local time zone at time of migration. * Newly created builds are untouched. * Does not throw {@link IOException} since we make a best effort to migrate but do not consider it fatal to job loading if we cannot. * @param dir as in {@link Job#getBuildDir} * @param jenkinsHome root directory of Jenkins (for logging only) * @return true if migration was performed */ public synchronized boolean migrate(File dir, @CheckForNull File jenkinsHome) { if (load(dir)) { LOGGER.log(FINER, "migration already performed for {0}", dir); return false; } if (!dir.isDirectory()) { LOGGER.log(/* normal during Job.movedTo */FINE, "{0} was unexpectedly missing", dir); return false; } LOGGER.log(INFO, "Migrating build records in {0}. See https://www.jenkins.io/redirect/build-record-migration for more information.", dir); doMigrate(dir); save(dir); return true; } private static final Pattern NUMBER_ELT = Pattern.compile("(?m)^ <number>(\\d+)</number>(\r?\n)"); private void doMigrate(File dir) { idToNumber = new TreeMap<>(); File[] kids = dir.listFiles(); // Need to process symlinks first so we can rename to them. List<File> kidsList = new ArrayList<>(Arrays.asList(kids)); Iterator<File> it = kidsList.iterator(); while (it.hasNext()) { File kid = it.next(); String name = kid.getName(); try { Integer.parseInt(name); } catch (NumberFormatException x) { LOGGER.log(FINE, "ignoring nonnumeric entry {0}", name); continue; } try { if (Util.isSymlink(kid)) { LOGGER.log(FINE, "deleting build number symlink {0} → {1}", new Object[] {name, Util.resolveSymlink(kid)}); } else if (kid.isDirectory()) { LOGGER.log(FINE, "ignoring build directory {0}", name); continue; } else { LOGGER.log(WARNING, "need to delete anomalous file entry {0}", name); } Util.deleteFile(kid); it.remove(); } catch (Exception x) { LOGGER.log(WARNING, "failed to process " + kid, x); } } it = kidsList.iterator(); while (it.hasNext()) { File kid = it.next(); try { String name = kid.getName(); try { Integer.parseInt(name); LOGGER.log(FINE, "skipping new build dir {0}", name); continue; } catch (NumberFormatException x) { // OK, next… } if (!kid.isDirectory()) { LOGGER.log(FINE, "skipping non-directory {0}", name); continue; } long timestamp; try { synchronized (legacyIdFormatter) { timestamp = legacyIdFormatter.parse(name).getTime(); } } catch (ParseException x) { LOGGER.log(WARNING, "found unexpected dir {0}", name); continue; } File buildXml = new File(kid, "build.xml"); if (!buildXml.isFile()) { LOGGER.log(WARNING, "found no build.xml in {0}", name); continue; } String xml = Files.readString(Util.fileToPath(buildXml), StandardCharsets.UTF_8); Matcher m = NUMBER_ELT.matcher(xml); if (!m.find()) { LOGGER.log(WARNING, "could not find <number> in {0}/build.xml", name); continue; } int number = Integer.parseInt(m.group(1)); String nl = m.group(2); xml = m.replaceFirst(" <id>" + name + "</id>" + nl + " <timestamp>" + timestamp + "</timestamp>" + nl); File newKid = new File(dir, Integer.toString(number)); move(kid, newKid); Files.writeString(Util.fileToPath(newKid).resolve("build.xml"), xml, StandardCharsets.UTF_8); LOGGER.log(FINE, "fully processed {0} → {1}", new Object[] {name, number}); idToNumber.put(name, number); } catch (Exception x) { LOGGER.log(WARNING, "failed to process " + kid, x); } } } /** * Tries to move/rename a file from one path to another. * Uses {@link java.nio.file.Files#move} when available. * Does not use {@link java.nio.file.StandardCopyOption#REPLACE_EXISTING} or any other options. * TODO candidate for moving to {@link Util} */ static void move(File src, File dest) throws IOException { try { Files.move(src.toPath(), dest.toPath()); } catch (IOException x) { throw x; } catch (RuntimeException x) { throw new IOException(x); } } /** * Look up a historical run by ID. * @param id a nonnumeric ID which may be a valid {@link Run#getId} * @return the corresponding {@link Run#number}, or 0 if unknown */ public synchronized int findNumber(@NonNull String id) { Integer number = idToNumber.get(id); return number != null ? number : 0; } /** * Delete the record of a build. * @param dir as in {@link Job#getBuildDir} * @param id a {@link Run#getId} */ public synchronized void delete(File dir, String id) { if (idToNumber.remove(id) != null) { save(dir); } } }
Dohbedoh/jenkins
core/src/main/java/jenkins/model/RunIdMigrator.java
214,087
404: Not Found
jetty/jetty.project
jetty-ee10/jetty-ee10-servlet/src/main/java/org/eclipse/jetty/ee10/servlet/Invoker.java
214,088
/** * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject.internal; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Objects; import com.google.common.collect.ImmutableMap; import com.google.inject.ConfigurationException; import com.google.inject.Guice; import com.google.inject.HierarchyTraversalFilter; import com.google.inject.TypeLiteral; import com.google.inject.util.Types; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; /** * Static methods for working with types that we aren't publishing in the * public {@code Types} API. * * @author [email protected] (Jesse Wilson) */ public class MoreTypes { public static final Type[] EMPTY_TYPE_ARRAY = new Type[] {}; private MoreTypes() {} private static final Map<TypeLiteral<?>, TypeLiteral<?>> PRIMITIVE_TO_WRAPPER = new ImmutableMap.Builder<TypeLiteral<?>, TypeLiteral<?>>() .put(TypeLiteral.get(boolean.class), TypeLiteral.get(Boolean.class)) .put(TypeLiteral.get(byte.class), TypeLiteral.get(Byte.class)) .put(TypeLiteral.get(short.class), TypeLiteral.get(Short.class)) .put(TypeLiteral.get(int.class), TypeLiteral.get(Integer.class)) .put(TypeLiteral.get(long.class), TypeLiteral.get(Long.class)) .put(TypeLiteral.get(float.class), TypeLiteral.get(Float.class)) .put(TypeLiteral.get(double.class), TypeLiteral.get(Double.class)) .put(TypeLiteral.get(char.class), TypeLiteral.get(Character.class)) .put(TypeLiteral.get(void.class), TypeLiteral.get(Void.class)) .build(); /** * Returns an type that's appropriate for use in a key. * * <p>If the raw type of {@code typeLiteral} is a {@code javax.inject.Provider}, this returns a * {@code com.google.inject.Provider} with the same type parameters. * * <p>If the type is a primitive, the corresponding wrapper type will be returned. * * @throws ConfigurationException if {@code type} contains a type variable */ public static <T> TypeLiteral<T> canonicalizeForKey(TypeLiteral<T> typeLiteral) { Type type = typeLiteral.getType(); if (!isFullySpecified(type)) { Errors errors = new Errors().keyNotFullySpecified(typeLiteral); throw new ConfigurationException(errors.getMessages()); } if (typeLiteral.getRawType() == javax.inject.Provider.class) { ParameterizedType parameterizedType = (ParameterizedType) type; // the following casts are generally unsafe, but com.google.inject.Provider extends // javax.inject.Provider and is covariant @SuppressWarnings("unchecked") TypeLiteral<T> guiceProviderType = (TypeLiteral<T>) TypeLiteral.get( Types.providerOf(parameterizedType.getActualTypeArguments()[0])); return guiceProviderType; } @SuppressWarnings("unchecked") TypeLiteral<T> wrappedPrimitives = (TypeLiteral<T>) PRIMITIVE_TO_WRAPPER.get(typeLiteral); return wrappedPrimitives != null ? wrappedPrimitives : typeLiteral; } /** * Returns true if {@code type} is free from type variables. */ private static boolean isFullySpecified(Type type) { if (type instanceof Class) { return true; } else if (type instanceof CompositeType) { return ((CompositeType) type).isFullySpecified(); } else if (type instanceof TypeVariable){ return false; } else { return ((CompositeType) canonicalize(type)).isFullySpecified(); } } /** * Returns a type that is functionally equal but not necessarily equal * according to {@link Object#equals(Object) Object.equals()}. The returned * type is {@link Serializable}. */ public static Type canonicalize(Type type) { if (type instanceof Class) { Class<?> c = (Class<?>) type; return c.isArray() ? new GenericArrayTypeImpl(canonicalize(c.getComponentType())) : c; } else if (type instanceof CompositeType) { return type; } else if (type instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType) type; return new ParameterizedTypeImpl(p.getOwnerType(), p.getRawType(), p.getActualTypeArguments()); } else if (type instanceof GenericArrayType) { GenericArrayType g = (GenericArrayType) type; return new GenericArrayTypeImpl(g.getGenericComponentType()); } else if (type instanceof WildcardType) { WildcardType w = (WildcardType) type; return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds()); } else { // type is either serializable as-is or unsupported return type; } } public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>) type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); checkArgument(rawType instanceof Class, "Expected a Class, but <%s> is of type %s", type, type.getClass().getName()); return (Class<?>) rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType)type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that'll won't work if there are multiple. // having a raw type that's more general than necessary is okay return Object.class; } else { throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + type.getClass().getName()); } } /** * Returns true if {@code a} and {@code b} are equal. */ public static boolean equals(Type a, Type b) { if (a == b) { // also handles (a == null && b == null) return true; } else if (a instanceof Class) { // Class already specifies equals(). return a.equals(b); } else if (a instanceof ParameterizedType) { if (!(b instanceof ParameterizedType)) { return false; } // TODO: save a .clone() call ParameterizedType pa = (ParameterizedType) a; ParameterizedType pb = (ParameterizedType) b; return Objects.equal(pa.getOwnerType(), pb.getOwnerType()) && pa.getRawType().equals(pb.getRawType()) && Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments()); } else if (a instanceof GenericArrayType) { if (!(b instanceof GenericArrayType)) { return false; } GenericArrayType ga = (GenericArrayType) a; GenericArrayType gb = (GenericArrayType) b; return equals(ga.getGenericComponentType(), gb.getGenericComponentType()); } else if (a instanceof WildcardType) { if (!(b instanceof WildcardType)) { return false; } WildcardType wa = (WildcardType) a; WildcardType wb = (WildcardType) b; return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds()) && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds()); } else if (a instanceof TypeVariable) { if (!(b instanceof TypeVariable)) { return false; } TypeVariable<?> va = (TypeVariable) a; TypeVariable<?> vb = (TypeVariable) b; return va.getGenericDeclaration().equals(vb.getGenericDeclaration()) && va.getName().equals(vb.getName()); } else { // This isn't a type we support. Could be a generic array type, wildcard type, etc. return false; } } private static int hashCodeOrZero(Object o) { return o != null ? o.hashCode() : 0; } public static String typeToString(Type type) { return type instanceof Class ? ((Class) type).getName() : type.toString(); } /** * Returns the generic supertype for {@code type}. For example, given a class {@code IntegerSet}, * the result for when supertype is {@code Set.class} is {@code Set<Integer>} and the result * when the supertype is {@code Collection.class} is {@code Collection<Integer>}. */ public static Type getGenericSupertype(Type type, Class<?> rawType, Class<?> toResolve) { if (toResolve == rawType) { return type; } // we skip searching through interfaces if unknown is an interface if (toResolve.isInterface()) { Class[] interfaces = rawType.getInterfaces(); for (int i = 0, length = interfaces.length; i < length; i++) { if (interfaces[i] == toResolve) { return rawType.getGenericInterfaces()[i]; } else if (toResolve.isAssignableFrom(interfaces[i])) { return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve); } } } // check our supertypes if (!rawType.isInterface()) { HierarchyTraversalFilter filter = Guice.createHierarchyTraversalFilter(); while (filter.isWorthScanning(rawType)) { Class<?> rawSupertype = rawType.getSuperclass(); if (rawSupertype == toResolve) { return getGenericSuperclass(rawType); } else if (toResolve.isAssignableFrom(rawSupertype)) { return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve); } rawType = rawSupertype; } } // we can't resolve this further return toResolve; } private static HashMap<Class<?>, Type> cacheGenericSuperclass = new HashMap<Class<?>, Type>(); public static Type getGenericSuperclass(Class<?> rawType) { Type t = cacheGenericSuperclass.get(rawType); if( t!=null ) return t; t = rawType.getGenericSuperclass(); cacheGenericSuperclass.put(rawType,t); return t; } public static Type resolveTypeVariable(Type type, Class<?> rawType, TypeVariable unknown) { Class<?> declaredByRaw = declaringClassOf(unknown); // we can't reduce this further if (declaredByRaw == null) { return unknown; } Type declaredBy = getGenericSupertype(type, rawType, declaredByRaw); if (declaredBy instanceof ParameterizedType) { int index = indexOf(declaredByRaw.getTypeParameters(), unknown); return ((ParameterizedType) declaredBy).getActualTypeArguments()[index]; } return unknown; } private static int indexOf(Object[] array, Object toFind) { for (int i = 0; i < array.length; i++) { if (toFind.equals(array[i])) { return i; } } throw new NoSuchElementException(); } /** * Returns the declaring class of {@code typeVariable}, or {@code null} if it was not declared by * a class. */ private static Class<?> declaringClassOf(TypeVariable typeVariable) { GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration(); return genericDeclaration instanceof Class ? (Class<?>) genericDeclaration : null; } public static class ParameterizedTypeImpl implements ParameterizedType, Serializable, CompositeType { private final Type ownerType; private final Type rawType; private final Type[] typeArguments; public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) { // require an owner type if the raw type needs it if (rawType instanceof Class<?>) { Class rawTypeAsClass = (Class) rawType; checkArgument(ownerType != null || rawTypeAsClass.getEnclosingClass() == null, "No owner type for enclosed %s", rawType); checkArgument(ownerType == null || rawTypeAsClass.getEnclosingClass() != null, "Owner type for unenclosed %s", rawType); } this.ownerType = ownerType == null ? null : canonicalize(ownerType); this.rawType = canonicalize(rawType); this.typeArguments = typeArguments.clone(); for (int t = 0; t < this.typeArguments.length; t++) { checkNotNull(this.typeArguments[t], "type parameter"); checkNotPrimitive(this.typeArguments[t], "type parameters"); this.typeArguments[t] = canonicalize(this.typeArguments[t]); } } public Type[] getActualTypeArguments() { return typeArguments.clone(); } public Type getRawType() { return rawType; } public Type getOwnerType() { return ownerType; } public boolean isFullySpecified() { if (ownerType != null && !MoreTypes.isFullySpecified(ownerType)) { return false; } if (!MoreTypes.isFullySpecified(rawType)) { return false; } for (Type type : typeArguments) { if (!MoreTypes.isFullySpecified(type)) { return false; } } return true; } @Override public boolean equals(Object other) { return other instanceof ParameterizedType && MoreTypes.equals(this, (ParameterizedType) other); } @Override public int hashCode() { return Arrays.hashCode(typeArguments) ^ rawType.hashCode() ^ hashCodeOrZero(ownerType); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(30 * (typeArguments.length + 1)); stringBuilder.append(typeToString(rawType)); if (typeArguments.length == 0) { return stringBuilder.toString(); } stringBuilder.append("<").append(typeToString(typeArguments[0])); for (int i = 1; i < typeArguments.length; i++) { stringBuilder.append(", ").append(typeToString(typeArguments[i])); } return stringBuilder.append(">").toString(); } private static final long serialVersionUID = 0; } public static class GenericArrayTypeImpl implements GenericArrayType, Serializable, CompositeType { private final Type componentType; public GenericArrayTypeImpl(Type componentType) { this.componentType = canonicalize(componentType); } public Type getGenericComponentType() { return componentType; } public boolean isFullySpecified() { return MoreTypes.isFullySpecified(componentType); } @Override public boolean equals(Object o) { return o instanceof GenericArrayType && MoreTypes.equals(this, (GenericArrayType) o); } @Override public int hashCode() { return componentType.hashCode(); } @Override public String toString() { return typeToString(componentType) + "[]"; } private static final long serialVersionUID = 0; } /** * The WildcardType interface supports multiple upper bounds and multiple * lower bounds. We only support what the Java 6 language needs - at most one * bound. If a lower bound is set, the upper bound must be Object.class. */ public static class WildcardTypeImpl implements WildcardType, Serializable, CompositeType { private final Type upperBound; private final Type lowerBound; public WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) { checkArgument(lowerBounds.length <= 1, "Must have at most one lower bound."); checkArgument(upperBounds.length == 1, "Must have exactly one upper bound."); if (lowerBounds.length == 1) { checkNotNull(lowerBounds[0], "lowerBound"); checkNotPrimitive(lowerBounds[0], "wildcard bounds"); checkArgument(upperBounds[0] == Object.class, "bounded both ways"); this.lowerBound = canonicalize(lowerBounds[0]); this.upperBound = Object.class; } else { checkNotNull(upperBounds[0], "upperBound"); checkNotPrimitive(upperBounds[0], "wildcard bounds"); this.lowerBound = null; this.upperBound = canonicalize(upperBounds[0]); } } public Type[] getUpperBounds() { return new Type[] { upperBound }; } public Type[] getLowerBounds() { return lowerBound != null ? new Type[] { lowerBound } : EMPTY_TYPE_ARRAY; } public boolean isFullySpecified() { return MoreTypes.isFullySpecified(upperBound) && (lowerBound == null || MoreTypes.isFullySpecified(lowerBound)); } @Override public boolean equals(Object other) { return other instanceof WildcardType && MoreTypes.equals(this, (WildcardType) other); } @Override public int hashCode() { // this equals Arrays.hashCode(getLowerBounds()) ^ Arrays.hashCode(getUpperBounds()); return (lowerBound != null ? 31 + lowerBound.hashCode() : 1) ^ (31 + upperBound.hashCode()); } @Override public String toString() { if (lowerBound != null) { return "? super " + typeToString(lowerBound); } else if (upperBound == Object.class) { return "?"; } else { return "? extends " + typeToString(upperBound); } } private static final long serialVersionUID = 0; } private static void checkNotPrimitive(Type type, String use) { checkArgument(!(type instanceof Class<?>) || !((Class) type).isPrimitive(), "Primitive types are not allowed in %s: %s", use, type); } /** A type formed from other types, such as arrays, parameterized types or wildcard types */ private interface CompositeType { /** Returns true if there are no type variables in this type. */ boolean isFullySpecified(); } }
Andlab/roboguice
guice/core/src/com/google/inject/internal/MoreTypes.java
214,089
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via [email protected] or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.apps; import java.util.ListResourceBundle; /** * Base Resource Bundle * * @author Jesse Jr * @version $Id: ALoginRes_pt.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ */ public final class ALoginRes_pt extends ListResourceBundle { /** Translation Content */ //Characters encoded to UTF8 Hex, so no more problems with svn commits //Fernando Lucktemberg - CenturuyOn Consultoria static final Object[][] contents = new String[][] { { "Connection", "Conex\u00e3o" }, { "Defaults", "Padr\u00f5es" }, { "Login", "ADempiere Login" }, { "File", "Arquivo" }, { "Exit", "Sair" }, { "Help", "Ajuda" }, { "About", "Sobre" }, { "Host", "Servidor" }, { "Database", "Banco de Dados" }, { "User", "Usu\u00e1rio" }, { "EnterUser", "Entre com o Usu\u00e1rio da Aplica\u00e7\u00e3o" }, { "Password", "Senha" }, { "EnterPassword", "Entre com a senha da Aplica\u00e7\u00e3o" }, { "Language", "Idioma" }, { "SelectLanguage", "Selecione o idioma" }, { "Role", "Regra" }, { "Client", "Cliente" }, { "Organization", "Organiza\u00e7\u00e3o" }, { "Date", "Data" }, { "Warehouse", "Dep\u00f3sito" }, { "Printer", "Impressora" }, { "Connected", "Conectado" }, { "NotConnected", "N\u00e3o conectado" }, { "DatabaseNotFound", "Banco de Dados n\u00e3o encontrado" }, { "UserPwdError", "Usu\u00e1rio/Senha inv\u00e1lidos" }, { "RoleNotFound", "Regra n\u00e3o encontrada/incorreta" }, { "Authorized", "Autorizado" }, { "Ok", "Ok" }, { "Cancel", "Cancelar" }, { "VersionConflict", "Conflito de Vers\u00f5es:" }, { "VersionInfo", "Servidor <> Cliente" }, { "PleaseUpgrade", "Favor executar o programa de atualiza��o" } }; /** * Get Contents * @return context */ public Object[][] getContents() { return contents; } // getContents } // ALoginRes_pt
alhudaghifari/adempiere
client/src/org/compiere/apps/ALoginRes_pt.java
214,090
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.common.inject; import org.opensearch.common.inject.binder.AnnotatedBindingBuilder; import org.opensearch.common.inject.binder.AnnotatedElementBuilder; import org.opensearch.common.inject.binder.LinkedBindingBuilder; import org.opensearch.common.inject.spi.Message; /** * A module whose configuration information is hidden from its environment by default. Only bindings * that are explicitly exposed will be available to other modules and to the users of the injector. * This module may expose the bindings it creates and the bindings of the modules it installs. * <p> * A private module can be nested within a regular module or within another private module using * {@link Binder#install install()}. Its bindings live in a new environment that inherits bindings, * type converters, scopes, and interceptors from the surrounding ("parent") environment. When you * nest multiple private modules, the result is a tree of environments where the injector's * environment is the root. * <p> * Guice EDSL bindings can be exposed with {@link #expose(Class) expose()}. {@literal @}{@link * org.opensearch.common.inject.Provides Provides} bindings can be exposed with the {@literal @}{@link * Exposed} annotation: * <pre> * public class FooBarBazModule extends PrivateModule { * protected void configure() { * bind(Foo.class).to(RealFoo.class); * expose(Foo.class); * * install(new TransactionalBarModule()); * expose(Bar.class).annotatedWith(Transactional.class); * * bind(SomeImplementationDetail.class); * install(new MoreImplementationDetailsModule()); * } * * {@literal @}Provides {@literal @}Exposed * public Baz provideBaz() { * return new SuperBaz(); * } * } * </pre> * <p> * The scope of a binding is constrained to its environment. A singleton bound in a private * module will be unique to its environment. But a binding for the same type in a different private * module will yield a different instance. * <p> * A shared binding that injects the {@code Injector} gets the root injector, which only has * access to bindings in the root environment. An explicit binding that injects the {@code Injector} * gets access to all bindings in the child environment. * <p> * To promote a just-in-time binding to an explicit binding, bind it: * <pre> * bind(FooImpl.class); * </pre> * * @author [email protected] (Jesse Wilson) * @since 2.0 * * @opensearch.internal */ public abstract class PrivateModule implements Module { /** * Like abstract module, the binder of the current private module */ private PrivateBinder binder; @Override public final synchronized void configure(Binder binder) { if (this.binder != null) { throw new IllegalStateException("Re-entry is not allowed."); } // Guice treats PrivateModules specially and passes in a PrivateBinder automatically. this.binder = (PrivateBinder) binder.skipSources(PrivateModule.class); try { configure(); } finally { this.binder = null; } } /** * Creates bindings and other configurations private to this module. Use {@link #expose(Class) * expose()} to make the bindings in this module available externally. */ protected abstract void configure(); /** * Makes the binding for {@code key} available to other modules and the injector. */ protected final <T> void expose(Key<T> key) { binder.expose(key); } /** * Makes a binding for {@code type} available to other modules and the injector. Use {@link * AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a * binding annotation. */ protected final AnnotatedElementBuilder expose(Class<?> type) { return binder.expose(type); } /** * Makes a binding for {@code type} available to other modules and the injector. Use {@link * AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a * binding annotation. */ protected final AnnotatedElementBuilder expose(TypeLiteral<?> type) { return binder.expose(type); } // everything below is copied from AbstractModule /** * Returns the current binder. */ protected final PrivateBinder binder() { return binder; } /** * @see Binder#bind(Key) */ protected final <T> LinkedBindingBuilder<T> bind(Key<T> key) { return binder.bind(key); } /** * @see Binder#bind(TypeLiteral) */ protected final <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral) { return binder.bind(typeLiteral); } /** * @see Binder#bind(Class) */ protected final <T> AnnotatedBindingBuilder<T> bind(Class<T> clazz) { return binder.bind(clazz); } /** * @see Binder#install(Module) */ protected final void install(Module module) { binder.install(module); } /** * @see Binder#addError(String, Object[]) */ protected final void addError(String message, Object... arguments) { binder.addError(message, arguments); } /** * @see Binder#addError(Throwable) */ protected final void addError(Throwable t) { binder.addError(t); } /** * @see Binder#addError(Message) */ protected final void addError(Message message) { binder.addError(message); } /** * @see Binder#getProvider(Key) */ protected final <T> Provider<T> getProvider(Key<T> key) { return binder.getProvider(key); } /** * @see Binder#getProvider(Class) */ protected final <T> Provider<T> getProvider(Class<T> type) { return binder.getProvider(type); } /** * @see Binder#getMembersInjector(Class) */ protected <T> MembersInjector<T> getMembersInjector(Class<T> type) { return binder.getMembersInjector(type); } /** * @see Binder#getMembersInjector(TypeLiteral) */ protected <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type) { return binder.getMembersInjector(type); } }
opensearch-project/OpenSearch
server/src/main/java/org/opensearch/common/inject/PrivateModule.java
214,091
/* * The MIT License * * Copyright 2013 Jesse Glick. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jenkins.model; import hudson.DescriptorExtensionList; import hudson.model.Descriptor; /** * Definition of a kind of artifact manager. * @see ArtifactManagerFactory * @since 1.532 */ public abstract class ArtifactManagerFactoryDescriptor extends Descriptor<ArtifactManagerFactory> { public static DescriptorExtensionList<ArtifactManagerFactory,ArtifactManagerFactoryDescriptor> all() { return Jenkins.getInstance().getDescriptorList(ArtifactManagerFactory.class); } }
KengoTODA/jenkins
core/src/main/java/jenkins/model/ArtifactManagerFactoryDescriptor.java
214,092
package com.baeldung.rules.jess; import com.baeldung.rules.jess.model.Answer; import com.baeldung.rules.jess.model.Question; import jess.Filter; import jess.JessException; import jess.Rete; import java.util.Iterator; import java.util.logging.Logger; public class JessWithData { public static final String RULES_BONUS_FILE = "bonus.clp"; private static Logger log = Logger.getLogger("JessWithData"); public static void main(String[] args) throws JessException { Rete engine = new Rete(); engine.reset(); engine.batch(RULES_BONUS_FILE); prepareData(engine); engine.run(); checkResults(engine); } private static void checkResults(Rete engine) { Iterator results = engine.getObjects(new Filter.ByClass(Answer.class)); while (results.hasNext()) { Answer answer = (Answer) results.next(); log.info(answer.toString()); } } private static void prepareData(Rete engine) throws JessException { Question question = new Question("Can I have a bonus?", -5); log.info(question.toString()); engine.add(question); } }
eugenp/tutorials
rule-engines-modules/jess/src/main/java/com/baeldung/rules/jess/JessWithData.java
214,093
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.common.inject.internal; import org.opensearch.common.inject.Binder; import org.opensearch.common.inject.Key; import org.opensearch.common.inject.binder.AnnotatedConstantBindingBuilder; import org.opensearch.common.inject.binder.ConstantBindingBuilder; import org.opensearch.common.inject.spi.Element; import java.lang.annotation.Annotation; import java.util.List; import static java.util.Collections.emptySet; /** * Bind a constant. * * @author [email protected] (Jesse Wilson) * * @opensearch.internal */ public final class ConstantBindingBuilderImpl<T> extends AbstractBindingBuilder<T> implements AnnotatedConstantBindingBuilder, ConstantBindingBuilder { @SuppressWarnings("unchecked") // constant bindings start out with T unknown public ConstantBindingBuilderImpl(Binder binder, List<Element> elements, Object source) { super(binder, elements, source, (Key<T>) NULL_KEY); } @Override public ConstantBindingBuilder annotatedWith(Class<? extends Annotation> annotationType) { annotatedWithInternal(annotationType); return this; } @Override public ConstantBindingBuilder annotatedWith(Annotation annotation) { annotatedWithInternal(annotation); return this; } @Override public void to(final String value) { toConstant(String.class, value); } @Override public void to(final int value) { toConstant(Integer.class, value); } @Override public void to(final long value) { toConstant(Long.class, value); } @Override public void to(final boolean value) { toConstant(Boolean.class, value); } @Override public void to(final double value) { toConstant(Double.class, value); } @Override public void to(final float value) { toConstant(Float.class, value); } @Override public void to(final short value) { toConstant(Short.class, value); } @Override public void to(final char value) { toConstant(Character.class, value); } @Override public void to(final Class<?> value) { toConstant(Class.class, value); } @Override public <E extends Enum<E>> void to(final E value) { toConstant(value.getDeclaringClass(), value); } private void toConstant(Class<?> type, Object instance) { // this type will define T, so these assignments are safe @SuppressWarnings("unchecked") Class<T> typeAsClassT = (Class<T>) type; @SuppressWarnings("unchecked") T instanceAsT = (T) instance; if (keyTypeIsSet()) { binder.addError(CONSTANT_VALUE_ALREADY_SET); return; } BindingImpl<T> base = getBinding(); Key<T> key; if (base.getKey().getAnnotation() != null) { key = Key.get(typeAsClassT, base.getKey().getAnnotation()); } else if (base.getKey().getAnnotationType() != null) { key = Key.get(typeAsClassT, base.getKey().getAnnotationType()); } else { key = Key.get(typeAsClassT); } if (instanceAsT == null) { binder.addError(BINDING_TO_NULL); } setBinding(new InstanceBindingImpl<>(base.getSource(), key, base.getScoping(), emptySet(), instanceAsT)); } @Override public String toString() { return "ConstantBindingBuilder"; } }
opensearch-project/OpenSearch
server/src/main/java/org/opensearch/common/inject/internal/ConstantBindingBuilderImpl.java
214,094
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.common.inject.spi; import org.opensearch.common.annotation.PublicApi; import org.opensearch.common.inject.Binder; import org.opensearch.common.inject.Scope; import java.lang.annotation.Annotation; import java.util.Objects; /** * Registration of a scope annotation with the scope that implements it. Instances are created * explicitly in a module using {@link org.opensearch.common.inject.Binder#bindScope(Class, Scope) bindScope()} * statements: * <pre> * Scope recordScope = new RecordScope(); * bindScope(RecordScoped.class, new RecordScope());</pre> * * @author [email protected] (Jesse Wilson) * @since 2.0 * * @opensearch.api */ @PublicApi(since = "1.0.0") public final class ScopeBinding implements Element { private final Object source; private final Class<? extends Annotation> annotationType; private final Scope scope; ScopeBinding(Object source, Class<? extends Annotation> annotationType, Scope scope) { this.source = Objects.requireNonNull(source, "source"); this.annotationType = Objects.requireNonNull(annotationType, "annotationType"); this.scope = Objects.requireNonNull(scope, "scope"); } @Override public Object getSource() { return source; } public Class<? extends Annotation> getAnnotationType() { return annotationType; } public Scope getScope() { return scope; } @Override public <T> T acceptVisitor(ElementVisitor<T> visitor) { return visitor.visit(this); } @Override public void applyTo(Binder binder) { binder.withSource(getSource()).bindScope(annotationType, scope); } }
opensearch-project/OpenSearch
server/src/main/java/org/opensearch/common/inject/spi/ScopeBinding.java
214,095
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.elasticsearch.common.inject.spi; import org.elasticsearch.common.inject.Binding; /** * A binding to the constructor of a concrete clss. To resolve injections, an instance is * instantiated by invoking the constructor. * * @author [email protected] (Jesse Wilson) * @since 2.0 */ public interface ConstructorBinding<T> extends Binding<T> { }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/inject/spi/ConstructorBinding.java
214,096
/* * Copyright (C) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.elasticsearch.common.inject; import org.elasticsearch.common.inject.internal.Errors; import org.elasticsearch.common.inject.spi.Message; import java.util.Collection; import java.util.Set; import static java.util.Collections.unmodifiableSet; import static org.elasticsearch.common.util.set.Sets.newHashSet; /** * Indicates that there was a runtime failure while providing an instance. * * @author [email protected] (Kevin Bourrillion) * @author [email protected] (Jesse Wilson) * @since 2.0 */ public final class ProvisionException extends RuntimeException { private final Set<Message> messages; /** * Creates a ConfigurationException containing {@code messages}. */ public ProvisionException(Iterable<Message> messages) { this.messages = unmodifiableSet(newHashSet(messages)); if (this.messages.isEmpty()) { throw new IllegalArgumentException(); } initCause(Errors.getOnlyCause(this.messages)); } /** * Returns messages for the errors that caused this exception. */ public Collection<Message> getErrorMessages() { return messages; } @Override public String getMessage() { return Errors.format("Guice provision errors", messages); } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/inject/ProvisionException.java
214,097
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.Serializable; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import java.util.Spliterator; import java.util.function.Predicate; import org.checkerframework.checker.nullness.qual.Nullable; /** * GWT emulated version of {@link ImmutableCollection}. * * @author Jesse Wilson */ @SuppressWarnings("serial") // we're overriding default serialization @ElementTypesAreNonnullByDefault public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable { static final int SPLITERATOR_CHARACTERISTICS = Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.ORDERED; ImmutableCollection() {} public abstract UnmodifiableIterator<E> iterator(); public boolean contains(@Nullable Object object) { return object != null && super.contains(object); } public final boolean add(E e) { throw new UnsupportedOperationException(); } public final boolean remove(@Nullable Object object) { throw new UnsupportedOperationException(); } public final boolean addAll(Collection<? extends E> newElements) { throw new UnsupportedOperationException(); } public final boolean removeAll(Collection<?> oldElements) { throw new UnsupportedOperationException(); } public final boolean removeIf(Predicate<? super E> predicate) { throw new UnsupportedOperationException(); } public final boolean retainAll(Collection<?> elementsToKeep) { throw new UnsupportedOperationException(); } public final void clear() { throw new UnsupportedOperationException(); } private transient @Nullable ImmutableList<E> asList; public ImmutableList<E> asList() { ImmutableList<E> list = asList; return (list == null) ? (asList = createAsList()) : list; } ImmutableList<E> createAsList() { switch (size()) { case 0: return ImmutableList.of(); case 1: return ImmutableList.of(iterator().next()); default: return new RegularImmutableAsList<E>(this, toArray()); } } /** If this collection is backed by an array of its elements in insertion order, returns it. */ Object @Nullable [] internalArray() { return null; } /** * If this collection is backed by an array of its elements in insertion order, returns the offset * where this collection's elements start. */ int internalArrayStart() { throw new UnsupportedOperationException(); } /** * If this collection is backed by an array of its elements in insertion order, returns the offset * where this collection's elements end. */ int internalArrayEnd() { throw new UnsupportedOperationException(); } static <E> ImmutableCollection<E> unsafeDelegate(Collection<E> delegate) { return new ForwardingImmutableCollection<E>(delegate); } boolean isPartialView() { return false; } /** GWT emulated version of {@link ImmutableCollection.Builder}. */ public abstract static class Builder<E> { Builder() {} static int expandedCapacity(int oldCapacity, int minCapacity) { if (minCapacity < 0) { throw new AssertionError("cannot store more than MAX_VALUE elements"); } // careful of overflow! int newCapacity = oldCapacity + (oldCapacity >> 1) + 1; if (newCapacity < minCapacity) { newCapacity = Integer.highestOneBit(minCapacity - 1) << 1; } if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; // guaranteed to be >= newCapacity } return newCapacity; } @CanIgnoreReturnValue public abstract Builder<E> add(E element); @CanIgnoreReturnValue public Builder<E> add(E... elements) { checkNotNull(elements); // for GWT for (E element : elements) { add(checkNotNull(element)); } return this; } @CanIgnoreReturnValue public Builder<E> addAll(Iterable<? extends E> elements) { checkNotNull(elements); // for GWT for (E element : elements) { add(checkNotNull(element)); } return this; } @CanIgnoreReturnValue public Builder<E> addAll(Iterator<? extends E> elements) { checkNotNull(elements); // for GWT while (elements.hasNext()) { add(checkNotNull(elements.next())); } return this; } public abstract ImmutableCollection<E> build(); } }
google/guava
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableCollection.java
214,098
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan; /** * An application using external memory may wish to synchronize access to that memory using semaphores. This extension enables an application to create semaphores from which non-Vulkan handles that reference the underlying synchronization primitive can be exported. * * <h5>Promotion to Vulkan 1.1</h5> * * <p>All functionality in this extension is included in core Vulkan 1.1, with the KHR suffix omitted. The original type, enum and command names are still available as aliases of the core functionality.</p> * * <dl> * <dt><b>Name String</b></dt> * <dd>{@code VK_KHR_external_semaphore}</dd> * <dt><b>Extension Type</b></dt> * <dd>Device extension</dd> * <dt><b>Registered Extension Number</b></dt> * <dd>78</dd> * <dt><b>Revision</b></dt> * <dd>1</dd> * <dt><b>Extension and Version Dependencies</b></dt> * <dd>{@link KHRExternalSemaphoreCapabilities VK_KHR_external_semaphore_capabilities}</dd> * <dt><b>Deprecation State</b></dt> * <dd><ul> * <li><em>Promoted</em> to <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.1-promotions">Vulkan 1.1</a></li> * </ul></dd> * <dt><b>Contact</b></dt> * <dd><ul> * <li>James Jones <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_external_semaphore]%20@cubanismo%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_external_semaphore%20extension*">cubanismo</a></li> * </ul></dd> * </dl> * * <h5>Other Extension Metadata</h5> * * <dl> * <dt><b>Last Modified Date</b></dt> * <dd>2016-10-21</dd> * <dt><b>IP Status</b></dt> * <dd>No known IP claims.</dd> * <dt><b>Contributors</b></dt> * <dd><ul> * <li>Faith Ekstrand, Intel</li> * <li>Jesse Hall, Google</li> * <li>Tobias Hector, Imagination Technologies</li> * <li>James Jones, NVIDIA</li> * <li>Jeff Juliano, NVIDIA</li> * <li>Matthew Netsch, Qualcomm Technologies, Inc.</li> * <li>Ray Smith, ARM</li> * <li>Lina Versace, Google</li> * </ul></dd> * </dl> */ public final class KHRExternalSemaphore { /** The extension specification version. */ public static final int VK_KHR_EXTERNAL_SEMAPHORE_SPEC_VERSION = 1; /** The extension name. */ public static final String VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME = "VK_KHR_external_semaphore"; /** Extends {@code VkStructureType}. */ public static final int VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR = 1000077000; /** Extends {@code VkSemaphoreImportFlagBits}. */ public static final int VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR = 0x1; private KHRExternalSemaphore() {} }
LWJGL/lwjgl3
modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/KHRExternalSemaphore.java