hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
5fa04ab4fd92af1f0ac634928c980cd847fbc053 | 1,039 | package xyz.mlserver.java.sql.db;
import org.bukkit.plugin.Plugin;
import xyz.mlserver.java.Log;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
public class DataBaseUtil {
private final Plugin plugin;
public DataBaseUtil(Plugin plugin) {
this.plugin = plugin;
}
public void debugException(Exception exc) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exc.printStackTrace(pw);
Log.toFile(sw.toString(), getPlugin());
Log.debug(sw.toString());
}
/**
* Debug.
*
* @param ex the ex
*/
public void debugSqlException(SQLException ex) {
Log.debug("§7An error has occurred with the database, the error code is: '" + ex.getErrorCode() + "'");
Log.debug("§7The state of the sql is: " + ex.getSQLState());
Log.debug("§7Error message: " + ex.getMessage());
debugException(ex);
}
public Plugin getPlugin() {
return plugin;
}
} | 25.975 | 111 | 0.628489 |
0ce63e0fea4b6f7033be6dd488060aed612fd2e6 | 795 | package com.study.empty.myTest;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
/**
* @Author: Dingpengfei
* @Description:插入排序 从第二位开始将数据放到合适的地方,后面的依次进行移动
* @Date: 2022/2/24 23:38
*/
public class InsertTest
{
@Test
public void test(){
int[] a = {5, 4, 11, 2, 1, 54, 8,12,45,4564};
for (int i = 1; i < a.length; i++) {
for (int j = i; j >0; j--) { //这里面从1开始往后 其实保证了前面的顺序都是一定的了
if (a[j-1]>a[j]){//每次从起始值开始挨个判断他们的差别就可
swap(a,j-1,j);
}
}
}
System.out.println(JSONObject.toJSON(a));
}
public void swap (int[]a ,int b, int c){
int temp = a[b];
a[b]=a[c];
a[c] =temp;
System.out.println(JSONObject.toJSON(a));
}
}
| 20.384615 | 69 | 0.513208 |
f87b7d682febb7bd4cbda378dcc47021f389084b | 8,436 | /*
* The MIT License
*
* Copyright 2018 Siggi.
*
* 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 io.siggi.nbt.v1_16_R1;
import com.mojang.authlib.GameProfile;
import io.siggi.nbt.NBTCompound;
import io.siggi.nbt.NBTList;
import com.mojang.datafixers.DataFixer;
import com.mojang.serialization.Dynamic;
import io.siggi.nbt.util.NBTUtil;
import net.minecraft.server.v1_16_R1.DataConverterTypes;
import net.minecraft.server.v1_16_R1.DynamicOpsNBT;
import net.minecraft.server.v1_16_R1.EntityInsentient;
import net.minecraft.server.v1_16_R1.EntityTypes;
import net.minecraft.server.v1_16_R1.IRegistry;
import net.minecraft.server.v1_16_R1.Item;
import net.minecraft.server.v1_16_R1.MinecraftKey;
import net.minecraft.server.v1_16_R1.NBTCompressedStreamTools;
import net.minecraft.server.v1_16_R1.NBTTagCompound;
import net.minecraft.server.v1_16_R1.NBTTagList;
import net.minecraft.server.v1_16_R1.World;
import net.minecraft.server.v1_16_R1.WorldServer;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.Skull;
import org.bukkit.craftbukkit.v1_16_R1.CraftServer;
import org.bukkit.craftbukkit.v1_16_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_16_R1.block.CraftSkull;
import org.bukkit.craftbukkit.v1_16_R1.enchantments.CraftEnchantment;
import org.bukkit.craftbukkit.v1_16_R1.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_16_R1.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_16_R1.util.CraftMagicNumbers;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.inventory.ItemStack;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
final class NBTUtilImpl extends NBTUtil {
@Override
public NBTCompound newCompound() {
return new NBTCompoundImpl();
}
@Override
public NBTList newList() {
return new NBTListImpl();
}
@Override
public <T> NBTCompound wrapCompound(T compound) {
return new NBTCompoundImpl((NBTTagCompound) compound);
}
@Override
public <T> NBTList wrapList(T list) {
return new NBTListImpl((NBTTagList) list);
}
@Override
public NBTCompound getTag(ItemStack stack) {
net.minecraft.server.v1_16_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(stack);
if (nmsStack.hasTag()) {
return wrapCompound(nmsStack.getTag());
} else {
return null;
}
}
@Override
public ItemStack setTag(ItemStack stack, NBTCompound compound) {
net.minecraft.server.v1_16_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(stack);
if (compound == null) {
nmsStack.setTag(null);
} else {
nmsStack.setTag(compound.getNMSCompound());
}
return CraftItemStack.asCraftMirror(nmsStack);
}
@Override
public NBTCompound itemToNBT(ItemStack stack) {
try {
net.minecraft.server.v1_16_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(stack);
NBTTagCompound nmsCompound = new NBTTagCompound();
nmsStack.save(nmsCompound);
NBTCompound compound = new NBTCompoundImpl(nmsCompound);
compound.setInt("DataVersion", getDataVersion());
return compound;
} catch (Exception e) {
return null;
}
}
@Override
public ItemStack itemFromNBT(NBTCompound compound) {
if (compound == null) {
return null;
}
try {
DataFixer dataConverterManager = ((CraftServer) Bukkit.getServer()).getHandle().getServer().dataConverterManager;
NBTCompound tempItem = compound.copy();
NBTTagCompound nmsCompound = (NBTTagCompound) dataConverterManager.update(
DataConverterTypes.ITEM_STACK,
new Dynamic(DynamicOpsNBT.a, tempItem.getNMSCompound()),
tempItem.getInt("DataVersion"),
getDataVersion()
).getValue();
net.minecraft.server.v1_16_R1.ItemStack nmsStack = net.minecraft.server.v1_16_R1.ItemStack.a(nmsCompound);
return CraftItemStack.asCraftMirror(nmsStack);
} catch (Exception e) {
return null;
}
}
private int dataVersion = -1;
private int getDataVersion() {
if (dataVersion == -1) {
dataVersion = CraftMagicNumbers.INSTANCE.getDataVersion();
}
return dataVersion;
}
@Override
public Class<NBTCompound> getCompoundClass() {
return NBTCompound.class;
}
@Override
public Class<NBTList> getListClass() {
return NBTList.class;
}
@Override
public Class<CraftItemStack> getCraftItemStack() {
return CraftItemStack.class;
}
@Override
public Entity summonEntity(NBTCompound nbtTag, Location location, CreatureSpawnEvent.SpawnReason reason) {
WorldServer worldserver = ((CraftWorld) location.getWorld()).getHandle();
World world = worldserver.getMinecraftWorld();
double x = location.getX();
double y = location.getY();
double z = location.getZ();
net.minecraft.server.v1_16_R1.Entity nmsEntity = EntityTypes.a(nbtTag.getNMSCompound(), worldserver, (ent) -> {
ent.setPositionRotation(x, y, z, ent.yaw, ent.pitch);
return !worldserver.addEntitySerialized(ent, reason) ? null : ent;
});
if (nmsEntity == null) {
return null;
}
nmsEntity.setPositionRotation(x, y, z, nmsEntity.yaw, nmsEntity.pitch);
return nmsEntity.getBukkitEntity();
}
@Override
public void setAI(Entity entity, boolean ai) {
net.minecraft.server.v1_16_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle();
if (nmsEntity instanceof EntityInsentient) {
EntityInsentient entityInsentient = (EntityInsentient) nmsEntity;
entityInsentient.setNoAI(!ai);
}
}
@Override
public boolean hasAI(Entity entity) {
net.minecraft.server.v1_16_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle();
if (nmsEntity instanceof EntityInsentient) {
EntityInsentient entityInsentient = (EntityInsentient) nmsEntity;
return !entityInsentient.isNoAI();
} else {
return false;
}
}
@Override
public String getItemName(ItemStack stack) {
net.minecraft.server.v1_16_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(stack);
NBTTagCompound nbttc = new NBTTagCompound();
nmsStack.save(nbttc);
NBTCompound compound = wrapCompound(nbttc);
String id = compound.getString("id");
Item item = (Item) IRegistry.ITEM.get(new MinecraftKey(id));
if (item == null) {
return "null";
} else {
return item.h(nmsStack).getString();
}
}
@Override
public String getEnchantmentName(Enchantment enchantment, int level) {
net.minecraft.server.v1_16_R1.Enchantment raw = CraftEnchantment.getRaw(enchantment);
return raw.d(level).getString();
}
@Override
public void setGameProfile(Skull skull, GameProfile profile) {
try {
Field profileField = CraftSkull.class.getDeclaredField("profile");
profileField.setAccessible(true);
profileField.set(skull, profile);
} catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException t) {
throw new RuntimeException(t);
}
}
@Override
public void serialize(OutputStream out, NBTCompound compound) throws IOException {
DataOutputStream dataOut = out instanceof DataOutputStream ? ((DataOutputStream) out) : new DataOutputStream(out);
NBTCompressedStreamTools.a(compound.getNMSCompound(), (DataOutput) dataOut);
}
@Override
public NBTCompound deserialize(InputStream in) throws IOException {
DataInputStream dataIn = in instanceof DataInputStream ? ((DataInputStream) in) : new DataInputStream(in);
return wrapCompound(NBTCompressedStreamTools.a(dataIn));
}
}
| 33.744 | 116 | 0.766596 |
04e73e01c3efbdfba204e1d965d101159eb76e05 | 505 | package com.ceiba.reserva.comando;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDate;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ComandoReserva {
private Long id;
private Long idCliente;
private String nombreCliente;
private Integer tipoVehiculo;
private LocalDate fechaInicio;
private LocalDate fechaFin;
private Integer numeroDias;
private Long valor;
}
| 20.2 | 34 | 0.782178 |
991b4051318dbee3042a95b9236d766ac77b97a2 | 1,762 | /*
* Copyright 2015-2017 GenerallyCloud.com
*
* 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.generallycloud.test.test;
import java.util.concurrent.CountDownLatch;
import com.generallycloud.baseio.log.DebugUtil;
public abstract class ITestThread implements Runnable {
private CountDownLatch latch;
private int time;
private long last_time;
protected void setTime(int time) {
this.time = time;
this.latch = new CountDownLatch(time);
}
public int getTime() {
return time;
}
public void await() throws InterruptedException {
latch.await();
}
public abstract void prepare() throws Exception;
public abstract void stop();
public void addCount(int passage) {
latch.countDown();
long c = latch.getCount();
if (c % passage == 0) {
long now = System.currentTimeMillis();
long passed = 0;
if (last_time == 0) {
last_time = now;
} else {
passed = now - last_time;
last_time = now;
}
DebugUtil.info("__________________________" + c + "\t" + "___" + passed);
}
}
}
| 24.472222 | 85 | 0.622588 |
8db987e6a6498b2ecb8c9e1c1f3ea11bec07e2c2 | 752 | package io.github.bennofs.wdumper.ext;
import com.github.luben.zstd.ZstdInputStream;
import org.wikidata.wdtk.dumpfiles.MwLocalDumpFile;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
public class ZstdDumpFile extends MwLocalDumpFile {
public ZstdDumpFile(String filepath) {
super(filepath);
}
@Override
public InputStream getDumpFileStream() throws IOException {
if (!this.getPath().toString().contains(".zst")) {
return super.getDumpFileStream();
}
return new ZstdInputStream(new BufferedInputStream(Files.newInputStream(this.getPath(), StandardOpenOption.READ)));
}
} | 31.333333 | 123 | 0.740691 |
f070bcd684af5c43849f4dfdb8669927f0dbdeff | 2,361 | package com.denizenscript.depenizen.bukkit.events.magicspells;
import com.nisovin.magicspells.events.SpellLearnEvent;
import com.denizenscript.denizen.utilities.implementation.BukkitScriptEntryData;
import com.denizenscript.denizen.events.BukkitScriptEvent;
import com.denizenscript.denizen.objects.PlayerTag;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.scripts.ScriptEntryData;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class SpellLearnScriptEvent extends BukkitScriptEvent implements Listener {
// <--[event]
// @Events
// magicspells player learns spell
//
// @Regex ^on magicspells [^\s]+ learns spell$
//
// @Triggers when a player is about to learn a spell.
//
// @Cancellable true
//
// @Context
// <context.spell_name> returns the name of the spell.
// <context.source> returns the source. Can either be SPELLBOOK, TEACH, TOME or OTHER
//
// @Plugin Depenizen, MagicSpells
//
// @Player Always.
//
// @Group Depenizen
//
// -->
public SpellLearnScriptEvent() {
instance = this;
}
public static SpellLearnScriptEvent instance;
public SpellLearnEvent event;
public PlayerTag player;
private ElementTag source;
private ElementTag spell;
@Override
public boolean couldMatch(ScriptPath path) {
return path.eventLower.startsWith("magicspells player learns spell");
}
@Override
public String getName() {
return "SpellLearnEvent";
}
@Override
public ScriptEntryData getScriptEntryData() {
return new BukkitScriptEntryData(player, null);
}
@Override
public ObjectTag getContext(String name) {
if (name.equals("source")) {
return source;
}
else if (name.equals("spell_name")) {
return spell;
}
return super.getContext(name);
}
@EventHandler
public void onPlayerCastsSpell(SpellLearnEvent event) {
player = PlayerTag.mirrorBukkitPlayer(event.getLearner());
spell = new ElementTag(event.getSpell().getName());
source = new ElementTag(event.getSource().name());
this.event = event;
fire(event);
}
}
| 28.445783 | 89 | 0.679373 |
55a8f4228d17d772a2b1bdb4ee4b387ba2de009f | 1,786 | // Copyright 2018 Delft University of Technology
//
// 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.List;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// import com.google.re2j.Matcher;
// import com.google.re2j.Pattern;
public class RemThread implements Callable<Boolean> {
private final String[] strings;
private final int start;
private final int stop;
private int[] matches;
private final Matcher[] matchers;
public RemThread(final String[] strings, final List<String> regexes, int[] matches, final int start, final int stop) {
this.strings = strings;
this.start = start;
this.stop = stop;
this.matches = matches;
final int np = regexes.size();
this.matchers = new Matcher[np];
for (int p = 0; p < np; p++) {
matchers[p] = Pattern.compile(regexes.get(p)).matcher("");
}
}
public Boolean call() {
int np = matches.length;
for (int i = start; i < stop; i++) {
for (int p = 0; p < np; p++) {
if (matchers[p].reset(strings[i]).matches()) {
matches[p]++;
}
}
}
return true;
}
}
| 31.333333 | 122 | 0.631019 |
7d3b0a796ca08230206c3d46eace1002fafa8f5b | 2,093 | package snownee.cuisine.world.gen;
import java.util.Random;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.BiomeSwamp;
import net.minecraft.world.gen.feature.WorldGenerator;
import net.minecraftforge.event.terraingen.DecorateBiomeEvent.Decorate;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import snownee.cuisine.CuisineConfig;
import snownee.cuisine.CuisineRegistry;
import snownee.cuisine.blocks.BlockModSapling.Type;
import snownee.cuisine.world.feature.WorldFeatureCitrusGenusTree;
public class WorldGenCitrusTrees
{
private static final Type[] TYPES = new Type[] { Type.CITRON, Type.CITRON, Type.CITRON, Type.LIME, Type.LIME, Type.LIME, Type.MANDARIN, Type.MANDARIN, Type.MANDARIN, Type.LIME, Type.LIME, Type.LEMON, Type.LEMON, Type.ORANGE, Type.ORANGE, Type.GRAPEFRUIT };
@SuppressWarnings("deprecation")
@SubscribeEvent
public void decorateEvent(Decorate event)
{
if (event.getType() == Decorate.EventType.TREE && event.getRand().nextInt(200) < CuisineConfig.WORLD_GEN.fruitTreesGenRate)
{
Random rand = event.getRand();
World world = event.getWorld();
BlockPos pos = event.getChunkPos().getBlock(rand.nextInt(16) + 8, 0, rand.nextInt(16) + 8);
Biome biome = world.getBiome(pos);
if (!biome.canRain() || biome.isSnowyBiome() || biome.decorator.treesPerChunk < 2 || biome.decorator.treesPerChunk > 10 || biome instanceof BiomeSwamp || rand.nextDouble() > biome.getDefaultTemperature())
{
return;
}
pos = WorldGenHelper.findGround(world, pos, false);
if (pos != null && pos.getY() < 100 && CuisineRegistry.SAPLING.canPlaceBlockAt(world, pos))
{
Type type = TYPES[rand.nextInt(TYPES.length)];
WorldGenerator generator = new WorldFeatureCitrusGenusTree(false, type, true);
generator.generate(world, rand, pos);
}
}
}
}
| 46.511111 | 260 | 0.690874 |
77be8b34e3c8cff017c866e4e4949bad382558db | 1,701 | /*
* Copyright 2015 Kim A. Betti, Alexey Zhokhov
*
* 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 grails.plugins.sitemapper.extension;
/**
* @author <a href='mailto:[email protected]'>Alexey Zhokhov</a>
*/
public enum Currency {
JPY, CNY, SDG, RON, MKD, MXN, CAD, ZAR, AUD, NOK, ILS, ISK, SYP, LYD, UYU, YER, CSD, EEK, THB, IDR, LBP, AED, BOB,
QAR, BHD, HNL, HRK, COP, ALL, DKK, MYR, SEK, RSD, BGN, DOP, KRW, LVL, VEF, CZK, TND, KWD, VND, JOD, NZD, PAB, CLP,
PEN, GBP, DZD, CHF, RUB, UAH, ARS, SAR, EGP, INR, PYG, TWD, TRY, BAM, OMR, SGD, MAD, BYR, NIO, HKD, LTL, SKK, GTQ,
BRL, EUR, HUF, IQD, CRC, PHP, SVC, PLN, USD, XBB, XBC, XBD, UGX, MOP, SHP, TTD, UYI, KGS, DJF, BTN, XBA, HTG, BBD,
XAU, FKP, MWK, PGK, XCD, COU, RWF, NGN, BSD, XTS, TMT, GEL, VUV, FJD, MVR, AZN, MNT, MGA, WST, KMF, GNF, SBD, BDT,
MMK, TJS, CVE, MDL, KES, SRD, LRD, MUR, CDF, BMD, USN, CUP, USS, GMD, UZS, CUC, ZMK, NPR, NAD, LAK, SZL, XDR, BND,
TZS, MXV, LSL, KYD, LKR, ANG, PKR, SLL, SCR, GHS, ERN, BOV, GIP, IRR, XPT, BWP, XFU, CLF, ETB, STD, XXX, XPD, AMD,
XPF, JMD, MRO, BIF, CHW, ZWL, AWG, MZN, CHE, XOF, KZT, BZD, XAG, KHR, XAF, GYD, AFN, SOS, TOP, AOA, KPW
}
| 51.545455 | 118 | 0.647266 |
69a867a14c05548a51381758137e8ed034dbbcd3 | 1,137 | package com.networknt.kafka.streams;
import com.networknt.config.Config;
import com.networknt.kafka.common.KafkaStreamsConfig;
import com.networknt.utility.ModuleRegistry;
import java.util.ArrayList;
import java.util.List;
public interface LightStreams {
/**
* Start the streams processing. The ip and port is for remote queries if the data is not
* on the current instance.
*
* @param ip ip address of the instance
* @param port port number that the service is bound
*/
void start(String ip, int port);
void close();
/**
* Register the module to the Registry so that the config can be shown in the server/info
*
*/
default void registerModule() {
// register the module with the configuration properties.
List<String> masks = new ArrayList<>();
masks.add("basic.auth.user.info");
masks.add("sasl.jaas.config");
masks.add("schema.registry.ssl.truststore.password");
ModuleRegistry.registerModule(LightStreams.class.getName(), Config.getInstance().getJsonMapConfigNoCache(KafkaStreamsConfig.CONFIG_NAME), masks);
}
}
| 33.441176 | 153 | 0.69569 |
eb7c229400f7aefad927974770aed95ed8e52719 | 2,817 | package com.spring.edu.Interceptor;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.spring.edu.vo.UsersVo;
import lombok.extern.slf4j.Slf4j;
/**
* @FileName : LoginCheckInterceptor.java
* @Project : hyun
* @Date : 2018. 7. 3.
* @작성자 : 유현재
* @변경이력 :
* @프로그램 설명 : 로그인 세션 관리 인터셉터 설정
*/
@Slf4j
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// session 객체를 가져옴
HttpSession session = request.getSession();
// login처리를 담당하는 사용자 정보를 담고 있는 객체를 가져옴
UsersVo usersVo = (UsersVo) session.getAttribute("login");
if ( usersVo == null ){
// 로그인이 안되어 있는 상태임으로 메인페이지로 다시 돌려보냄(redirect)
response.setContentType("text/html; charset=UTF-8");
PrintWriter printwriter = response.getWriter();
printwriter.print("<script>alert('로그인 후 이용가능합니다.'); history.go(-1);</script>");
printwriter.flush();
return false; // 더이상 컨트롤러 요청으로 가지 않도록 false로 반환함
}else if(request.getRequestURI().contains("admin")) {
if(usersVo.getUrGrade().equals("admin")) {
return true;
}else if(usersVo.getUrGrade().equals("USER")){
response.setContentType("text/html; charset=UTF-8");
PrintWriter printwriter = response.getWriter();
printwriter.print("<script>alert('권한이 없습니다.'); history.go(-1);</script>");
printwriter.flush();
/*response.sendRedirect("/");*/
return false;
}
}
// preHandle의 return은 컨트롤러 요청 uri로 가도 되냐 안되냐를 허가하는 의미임
// 따라서 true로하면 컨트롤러 uri로 가게 됨.
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
super.afterCompletion(request, response, handler, ex);
}
@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
super.afterConcurrentHandlingStarted(request, response, handler);
}
}
| 34.353659 | 118 | 0.655307 |
0cfd68c8587ee30130cce08b86dd908d7b0479ba | 8,333 | package mtr.render;
import mtr.block.BlockRailwaySign;
import mtr.block.BlockStationNameBase;
import mtr.block.IBlock;
import mtr.data.NameColorDataBase;
import mtr.data.Platform;
import mtr.data.RailwayData;
import mtr.data.Station;
import mtr.entity.EntitySeat;
import mtr.gui.ClientData;
import mtr.gui.IGui;
import net.minecraft.block.BlockState;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher;
import net.minecraft.client.render.block.entity.BlockEntityRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.client.util.math.Vector3f;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.WorldAccess;
import java.util.*;
import java.util.stream.Collectors;
public class RenderRailwaySign<T extends BlockRailwaySign.TileEntityRailwaySign> extends BlockEntityRenderer<T> implements IBlock, IGui {
public RenderRailwaySign(BlockEntityRenderDispatcher dispatcher) {
super(dispatcher);
}
@Override
public void render(T entity, float tickDelta, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay) {
final WorldAccess world = entity.getWorld();
if (world == null) {
return;
}
final BlockPos pos = entity.getPos();
final BlockState state = world.getBlockState(pos);
if (!(state.getBlock() instanceof BlockRailwaySign)) {
return;
}
final BlockRailwaySign block = (BlockRailwaySign) state.getBlock();
if (entity.getSign().length != block.length) {
return;
}
final Direction facing = IBlock.getStatePropertySafe(state, BlockStationNameBase.FACING);
final BlockRailwaySign.SignType[] signTypes = entity.getSign();
boolean renderBackground = false;
int backgroundColor = 0;
for (BlockRailwaySign.SignType signType : signTypes) {
if (signType != null) {
renderBackground = true;
if (signType.backgroundColor != 0) {
backgroundColor = signType.backgroundColor;
break;
}
}
}
matrices.push();
matrices.translate(0.5, 0.53125, 0.5);
matrices.multiply(Vector3f.POSITIVE_Y.getDegreesQuaternion(-facing.asRotation()));
matrices.multiply(Vector3f.POSITIVE_Z.getDegreesQuaternion(180));
matrices.translate(block.getXStart() / 16F - 0.5, 0, -0.0625 - SMALL_OFFSET * 3);
if (renderBackground) {
IGui.drawRectangle(matrices, vertexConsumers, 0, 0, 0.5F * (signTypes.length), 0.5F, SMALL_OFFSET * 2, facing, backgroundColor + ARGB_BLACK, -1);
}
for (int i = 0; i < signTypes.length; i++) {
if (signTypes[i] != null) {
final int index = i;
drawSign(matrices, vertexConsumers, dispatcher.getTextRenderer(), pos, signTypes[i], 0.5F * i, 0, 0.5F, i, signTypes.length - i - 1, entity.getSelectedIds(), facing, (x, y, size, flipTexture) -> IGui.drawTexture(matrices, vertexConsumers, signTypes[index].id.toString(), x, y, size, size, flipTexture ? 1 : 0, 0, flipTexture ? 0 : 1, 1, facing, -1, -1));
}
}
matrices.pop();
}
@Override
public boolean rendersOutsideBoundingBox(T blockEntity) {
return true;
}
public static void drawSign(MatrixStack matrices, VertexConsumerProvider vertexConsumers, TextRenderer textRenderer, BlockPos pos, BlockRailwaySign.SignType signType, float x, float y, float size, float maxWidthLeft, float maxWidthRight, Set<Long> selectedIds, Direction facing, DrawTexture drawTexture) {
if (RenderSeat.shouldNotRender(pos, EntitySeat.DETAIL_RADIUS)) {
return;
}
final float signSize = (signType.small ? BlockRailwaySign.SMALL_SIGN_PERCENTAGE : 1) * size;
final float margin = (size - signSize) / 2;
final boolean hasCustomText = signType.hasCustomText;
final boolean flipCustomText = signType.flipCustomText;
final boolean flipTexture = signType.flipTexture;
if (vertexConsumers != null && (signType == BlockRailwaySign.SignType.LINE || signType == BlockRailwaySign.SignType.LINE_FLIPPED)) {
final Station station = ClientData.getStation(pos);
if (station == null) {
return;
}
final Map<Integer, ClientData.ColorNamePair> routesInStation = ClientData.routesInStation.get(station.id);
if (routesInStation != null) {
final List<ClientData.ColorNamePair> selectedIdsSorted = selectedIds.stream().filter(selectedId -> RailwayData.isBetween(selectedId, Integer.MIN_VALUE, Integer.MAX_VALUE)).map(Math::toIntExact).filter(routesInStation::containsKey).map(routesInStation::get).sorted(Comparator.comparingInt(route -> route.color)).collect(Collectors.toList());
final int selectedCount = selectedIdsSorted.size();
final float maxWidth = Math.max(0, ((flipCustomText ? maxWidthLeft : maxWidthRight) + 1) * size - margin * 1.5F);
final List<Float> textWidths = new ArrayList<>();
for (final ClientData.ColorNamePair route : selectedIdsSorted) {
IGui.drawStringWithFont(matrices, textRenderer, route.name, HorizontalAlignment.LEFT, VerticalAlignment.CENTER, 0, 10000, -1, size - margin * 3, 1, 0, false, (x1, y1, x2, y2) -> textWidths.add(x2));
}
matrices.push();
matrices.translate(flipCustomText ? x + size - margin : x + margin, 0, 0);
final float totalTextWidth = textWidths.stream().reduce(Float::sum).orElse(0F) + 1.5F * margin * selectedCount;
if (totalTextWidth > maxWidth) {
matrices.scale((maxWidth - margin / 2) / (totalTextWidth - margin / 2), 1, 1);
}
float xOffset = margin * 0.5F;
for (int i = 0; i < selectedIdsSorted.size(); i++) {
final ClientData.ColorNamePair route = selectedIdsSorted.get(i);
IGui.drawStringWithFont(matrices, textRenderer, route.name, flipCustomText ? HorizontalAlignment.RIGHT : HorizontalAlignment.LEFT, VerticalAlignment.TOP, flipCustomText ? -xOffset : xOffset, y + margin * 1.5F, -1, size - margin * 3, 0.01F, ARGB_WHITE, false, (x1, y1, x2, y2) -> IGui.drawRectangle(matrices, vertexConsumers, x1 - margin / 2, y1 - margin / 2, x2 + margin / 2, y2 + margin / 2, SMALL_OFFSET, facing, route.color + ARGB_BLACK, -1));
xOffset += textWidths.get(i) + margin * 1.5F;
}
matrices.pop();
}
} else if (vertexConsumers != null && (signType == BlockRailwaySign.SignType.PLATFORM || signType == BlockRailwaySign.SignType.PLATFORM_FLIPPED)) {
final Station station = ClientData.getStation(pos);
if (station == null) {
return;
}
final Map<Long, Platform> platformPositions = ClientData.platformsInStation.get(station.id);
if (platformPositions != null) {
final List<Platform> selectedIdsSorted = selectedIds.stream().filter(platformPositions::containsKey).map(platformPositions::get).sorted(NameColorDataBase::compareTo).collect(Collectors.toList());
final int selectedCount = selectedIdsSorted.size();
final float smallPadding = margin / selectedCount;
final float height = (size - margin * 2 + smallPadding) / selectedCount;
for (int i = 0; i < selectedIdsSorted.size(); i++) {
final float topOffset = i * height + margin;
final float bottomOffset = (i + 1) * height + margin - smallPadding;
final RouteRenderer routeRenderer = new RouteRenderer(matrices, vertexConsumers, selectedIdsSorted.get(i), true);
routeRenderer.renderArrow((flipCustomText ? x - maxWidthLeft * size : x) + margin, (flipCustomText ? x + size : x + (maxWidthRight + 1) * size) - margin, topOffset, bottomOffset, flipCustomText, !flipCustomText, facing, -1, false);
}
}
} else {
drawTexture.drawTexture(x + margin, y + margin, signSize, flipTexture);
if (hasCustomText) {
final float fixedMargin = size * (1 - BlockRailwaySign.SMALL_SIGN_PERCENTAGE) / 2;
final boolean isSmall = signType.small;
final float maxWidth = Math.max(0, (flipCustomText ? maxWidthLeft : maxWidthRight) * size - fixedMargin * (isSmall ? 1 : 2));
final float start = flipCustomText ? x - (isSmall ? 0 : fixedMargin) : x + size + (isSmall ? 0 : fixedMargin);
IGui.drawStringWithFont(matrices, textRenderer, signType.text, flipCustomText ? HorizontalAlignment.RIGHT : HorizontalAlignment.LEFT, VerticalAlignment.TOP, start, y + fixedMargin, maxWidth, size - fixedMargin * 2, 0.01F, ARGB_WHITE, false, null);
}
}
}
@FunctionalInterface
public interface DrawTexture {
void drawTexture(float x, float y, float size, boolean flipTexture);
}
}
| 48.447674 | 451 | 0.731549 |
bd46aedf8ba86a9f23a5e060e196b5448862e2c3 | 16,308 | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.volatility.surface;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.LocalDate;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.model.interestrate.curve.ForwardCurve;
import com.opengamma.analytics.financial.model.volatility.BlackFormulaRepository;
import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.core.marketdatasnapshot.VolatilitySurfaceData;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.SurfaceAndCubePropertyNames;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.analytics.model.FutureOptionExpiries;
import com.opengamma.financial.analytics.model.InstrumentTypeProperties;
import com.opengamma.financial.analytics.model.curve.forward.ForwardCurveValuePropertyNames;
import com.opengamma.financial.analytics.model.equity.EquitySecurityUtils;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdentifiable;
import com.opengamma.id.ExternalScheme;
import com.opengamma.util.time.Tenor;
import com.opengamma.util.tuple.Pair;
import com.opengamma.util.tuple.Pairs;
/**
*
*/
public class EquityFutureOptionVolatilitySurfaceDataFunction extends AbstractFunction.NonCompiledInvoker {
/** The logger */
private static final Logger s_logger = LoggerFactory.getLogger(EquityFutureOptionVolatilitySurfaceDataFunction.class);
/** The supported schemes */
private static final Set<ExternalScheme> s_validSchemes = ImmutableSet.of(ExternalSchemes.BLOOMBERG_TICKER, ExternalSchemes.BLOOMBERG_TICKER_WEAK, ExternalSchemes.ACTIVFEED_TICKER);
private ConfigDBVolatilitySurfaceSpecificationSource _volatilitySurfaceSpecificationSource;
@Override
public void init(final FunctionCompilationContext context) {
_volatilitySurfaceSpecificationSource = ConfigDBVolatilitySurfaceSpecificationSource.init(context, this);
}
@Override
/**
* {@inheritDoc} <p>
* INPUT: We are taking a VolatilitySurfaceData object, which contains all number of missing data, plus strikes and vols are in percentages <p>
* OUTPUT: and converting this into a StandardVolatilitySurfaceData object, which has no empty values, expiry is in years, and the strike and vol scale is without unit (35% -> 0.35)
*/
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
final ZonedDateTime valTime = ZonedDateTime.now(executionContext.getValuationClock());
final LocalDate valDate = valTime.toLocalDate();
final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
final Object specificationObject = inputs.getValue(ValueRequirementNames.VOLATILITY_SURFACE_SPEC);
if (specificationObject == null) {
throw new OpenGammaRuntimeException("Could not get volatility surface specification");
}
final VolatilitySurfaceSpecification specification = (VolatilitySurfaceSpecification) specificationObject;
final String surfaceQuoteUnits = specification.getQuoteUnits();
// Get the volatility surface data object
final Object rawSurfaceObject = inputs.getValue(ValueRequirementNames.VOLATILITY_SURFACE_DATA);
if (rawSurfaceObject == null) {
throw new OpenGammaRuntimeException("Could not get volatility surface");
}
@SuppressWarnings("unchecked")
final VolatilitySurfaceData<Pair<Integer, Tenor>, Double> rawSurface = (VolatilitySurfaceData<Pair<Integer, Tenor>, Double>) rawSurfaceObject;
final VolatilitySurfaceData<Double, Double> stdVolSurface;
if (surfaceQuoteUnits.equals(SurfaceAndCubePropertyNames.VOLATILITY_QUOTE)) {
stdVolSurface = getSurfaceFromVolatilityQuote(valDate, rawSurface);
} else if (surfaceQuoteUnits.equals(SurfaceAndCubePropertyNames.PRICE_QUOTE)) {
// Get the forward curve
final Object forwardCurveObject = inputs.getValue(ValueRequirementNames.FORWARD_CURVE);
if (forwardCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get forward curve");
}
final ForwardCurve forwardCurve = (ForwardCurve) forwardCurveObject;
stdVolSurface = getSurfaceFromPriceQuote(valDate, rawSurface, forwardCurve, specification);
} else {
throw new OpenGammaRuntimeException("Cannot handle quote units " + surfaceQuoteUnits);
}
// Return
final ValueProperties constraints = desiredValue.getConstraints().copy().with(ValuePropertyNames.FUNCTION, getUniqueId()).get();
final ValueSpecification stdVolSpec = new ValueSpecification(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA, target.toSpecification(), constraints);
return Collections.singleton(new ComputedValue(stdVolSpec, stdVolSurface));
}
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.PRIMITIVE; // Bloomberg ticker, weak ticker or Activ ticker
}
@Override
public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) {
if (target.getValue() instanceof ExternalIdentifiable) {
final ExternalId identifier = ((ExternalIdentifiable) target.getValue()).getExternalId();
return s_validSchemes.contains(identifier.getScheme());
}
return false;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
final ValueProperties properties = ValueProperties.all();
final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA, target.toSpecification(), properties);
return Collections.singleton(spec);
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
// Function requires a VolatilitySurfaceData
// Build the surface name, in two parts: the given name and the target
final ValueProperties constraints = desiredValue.getConstraints();
final Set<String> instrumentTypes = constraints.getValues(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE);
if (instrumentTypes != null && instrumentTypes.size() == 1) {
if (!Iterables.getOnlyElement(instrumentTypes).equals(InstrumentTypeProperties.EQUITY_FUTURE_OPTION)) {
return null;
}
}
final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE);
if (surfaceNames == null || surfaceNames.size() != 1) {
s_logger.error("Function takes only get a single surface. Asked for {}", surfaceNames);
return null;
}
final String givenName = Iterables.getOnlyElement(surfaceNames);
final String fullName = givenName + "_" + EquitySecurityUtils.getTrimmedTarget(((ExternalIdentifiable) target.getValue()).getExternalId());
final VolatilitySurfaceSpecification specification = _volatilitySurfaceSpecificationSource.getSpecification(fullName, InstrumentTypeProperties.EQUITY_FUTURE_OPTION);
if (specification == null) {
s_logger.error("Could not get volatility surface specification with name " + fullName);
return null;
}
final String quoteUnits = specification.getQuoteUnits();
final ValueProperties properties = ValueProperties.builder()
.with(ValuePropertyNames.SURFACE, givenName)
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.EQUITY_FUTURE_OPTION)
.with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, specification.getSurfaceQuoteType())
.with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_UNITS, quoteUnits).get();
final ValueProperties fullNameProperties = ValueProperties.builder()
.with(ValuePropertyNames.SURFACE, givenName)
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.EQUITY_FUTURE_OPTION)
.with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, specification.getSurfaceQuoteType())
.with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_UNITS, quoteUnits).get();
final ValueRequirement surfaceReq = new ValueRequirement(ValueRequirementNames.VOLATILITY_SURFACE_DATA, target.toSpecification(), properties);
final ValueRequirement specificationReq = new ValueRequirement(ValueRequirementNames.VOLATILITY_SURFACE_SPEC, target.toSpecification(), properties);
final Set<ValueRequirement> requirements = new HashSet<>();
requirements.add(surfaceReq);
requirements.add(specificationReq);
if (quoteUnits.equals(SurfaceAndCubePropertyNames.PRICE_QUOTE)) {
final Set<String> curveNames = constraints.getValues(ValuePropertyNames.CURVE);
if (curveNames == null || curveNames.size() != 1) {
return null;
}
final String curveName = Iterables.getOnlyElement(curveNames);
//TODO get rid of hard-coding and add to properties
final String curveCalculationMethod = ForwardCurveValuePropertyNames.PROPERTY_YIELD_CURVE_IMPLIED_METHOD;
final ValueProperties curveProperties = ValueProperties.builder().with(ValuePropertyNames.CURVE, curveName)
.with(ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_CALCULATION_METHOD, curveCalculationMethod).get();
final ValueRequirement forwardCurveRequirement = new ValueRequirement(ValueRequirementNames.FORWARD_CURVE, target.toSpecification(), curveProperties);
requirements.add(forwardCurveRequirement);
}
return requirements;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) {
final ValueProperties.Builder properties = createValueProperties().with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.EQUITY_FUTURE_OPTION);
boolean surfaceNameSet = false;
for (final Map.Entry<ValueSpecification, ValueRequirement> entry : inputs.entrySet()) {
final ValueSpecification key = entry.getKey();
if (key.getValueName().equals(ValueRequirementNames.VOLATILITY_SURFACE_DATA)) {
properties.with(ValuePropertyNames.SURFACE, key.getProperty(ValuePropertyNames.SURFACE));
surfaceNameSet = true;
} else if (key.getValueName().equals(ValueRequirementNames.FORWARD_CURVE)) {
final ValueProperties curveProperties = key.getProperties().copy().withoutAny(ValuePropertyNames.FUNCTION).get();
for (final String property : curveProperties.getProperties()) {
properties.with(property, curveProperties.getValues(property));
}
//don't check if forward curve is set, because it isn't needed if the quotes are volatility
}
}
assert surfaceNameSet;
return Collections.singleton(new ValueSpecification(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA, target.toSpecification(), properties.get()));
}
private static VolatilitySurfaceData<Double, Double> getSurfaceFromVolatilityQuote(final LocalDate valDate, final VolatilitySurfaceData<Pair<Integer, Tenor>, Double> rawSurface) {
// Remove empties, convert expiries from number to years, and scale vols
final Map<Pair<Double, Double>, Double> volValues = new HashMap<>();
final DoubleArrayList tList = new DoubleArrayList();
final DoubleArrayList kList = new DoubleArrayList();
for (final Pair<Integer, Tenor> nthExpiry : rawSurface.getXs()) {
final double t = FutureOptionExpiries.EQUITY_FUTURE.getFutureOptionTtm(nthExpiry.getFirst(), valDate, nthExpiry.getSecond()); //TODO need information about expiry calculator
if (t > 5. / 365.) { // Bootstrapping vol surface to this data causes far more trouble than any gain. The data simply isn't reliable.
for (final Double strike : rawSurface.getYs()) {
final Double vol = rawSurface.getVolatility(nthExpiry, strike);
if (vol != null) {
tList.add(t);
kList.add(strike);
volValues.put(Pairs.of(t, strike), vol / 100.);
}
}
}
}
final VolatilitySurfaceData<Double, Double> stdVolSurface = new VolatilitySurfaceData<>(rawSurface.getDefinitionName(), rawSurface.getSpecificationName(), rawSurface.getTarget(),
tList.toArray(new Double[0]), kList.toArray(new Double[0]), volValues);
return stdVolSurface;
}
private static VolatilitySurfaceData<Double, Double> getSurfaceFromPriceQuote(final LocalDate valDate, final VolatilitySurfaceData<Pair<Integer, Tenor>, Double> rawSurface,
final ForwardCurve forwardCurve, final VolatilitySurfaceSpecification specification) {
final String surfaceQuoteType = specification.getSurfaceQuoteType();
double callAboveStrike = 0;
if (specification.getSurfaceInstrumentProvider() instanceof CallPutSurfaceInstrumentProvider) {
callAboveStrike = ((CallPutSurfaceInstrumentProvider<?, ?>) specification.getSurfaceInstrumentProvider()).useCallAboveStrike();
}
// Remove empties, convert expiries from number to years, and imply vols
final Map<Pair<Double, Double>, Double> volValues = new HashMap<>();
final DoubleArrayList tList = new DoubleArrayList();
final DoubleArrayList kList = new DoubleArrayList();
for (final Pair<Integer, Tenor> nthExpiry : rawSurface.getXs()) {
final double t = FutureOptionExpiries.EQUITY_FUTURE.getFutureOptionTtm(nthExpiry.getFirst(), valDate, nthExpiry.getSecond()); //TODO need information about expiry calculator
final double forward = forwardCurve.getForward(t);
if (t > 5. / 365.) { // Bootstrapping vol surface to this data causes far more trouble than any gain. The data simply isn't reliable.
for (final Double strike : rawSurface.getYs()) {
final Double price = rawSurface.getVolatility(nthExpiry, strike);
if (price != null) {
try {
final double vol;
if (surfaceQuoteType.equals(SurfaceAndCubeQuoteType.CALL_STRIKE)) {
vol = BlackFormulaRepository.impliedVolatility(price, forward, strike, t, true);
} else if (surfaceQuoteType.equals(SurfaceAndCubeQuoteType.PUT_STRIKE)) {
vol = BlackFormulaRepository.impliedVolatility(price, forward, strike, t, false);
} else if (surfaceQuoteType.equals(SurfaceAndCubeQuoteType.CALL_AND_PUT_STRIKE)) {
final boolean isCall = strike > callAboveStrike ? true : false;
vol = BlackFormulaRepository.impliedVolatility(price, forward, strike, t, isCall);
} else {
throw new OpenGammaRuntimeException("Cannot handle surface quote type " + surfaceQuoteType);
}
tList.add(t);
kList.add(strike);
volValues.put(Pairs.of(t, strike), vol);
} catch (final Exception e) {
}
}
}
}
}
final VolatilitySurfaceData<Double, Double> stdVolSurface = new VolatilitySurfaceData<>(rawSurface.getDefinitionName(), rawSurface.getSpecificationName(), rawSurface.getTarget(),
tList.toArray(new Double[0]), kList.toArray(new Double[0]), volValues);
return stdVolSurface;
}
}
| 58.035587 | 190 | 0.767967 |
864556189ed5755a2db11a21d448fe54a041b6d5 | 447 | package com.vlados.lab3.main.models;
public class Validator {
public float checkNumber(String string) throws IllegalArgumentException {
float num;
num = Float.parseFloat(string);
if(num >= 1) return num;
throw new IllegalArgumentException();
}
public String checkString(String s) throws IllegalArgumentException{
if(s.isEmpty()) throw new IllegalArgumentException();
return s;
}
}
| 27.9375 | 77 | 0.675615 |
bf9a51a1bd5ef901cc6d2507b4c45815e906aeca | 3,786 | package io.github.winsontse.hearteyes.util;
import android.annotation.SuppressLint;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by hao.xie on 16/5/10.
*/
public class TimeUtil {
private static Calendar calendar;
public static Calendar getCalendar() {
if (calendar == null) {
synchronized (TimeUtil.class) {
if (calendar == null) {
calendar = Calendar.getInstance();
}
}
}
return calendar;
}
/**
* 转换为多少时间前
*
* @param createTime
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String parseTime(long createTime) {
if (createTime == -1) {
return "刚刚";
}
String result = "";
String timeStr = "";
long nowLongTime = System.currentTimeMillis();
long distanceSeconds = (nowLongTime - createTime) / 1000;
if (distanceSeconds <= 60) {
result = "刚刚";
} else if (distanceSeconds <= 60 * 60) {
result = distanceSeconds / 60 + "分钟前";
} else if (distanceSeconds <= 24 * 60 * 60) {
result = distanceSeconds / 60 / 60 + "小时前";
} else if (distanceSeconds <= 7 * 24 * 60 * 60) {
result = distanceSeconds / 60 / 60 / 24 + "天前";
} else {
timeStr = getFormatTime(createTime, "yyyy-MM-dd");
result = timeStr;
}
return result;
}
@SuppressLint("SimpleDateFormat")
public static String getFormatTime(long time, String format) {
String result = "";
try {
result = new SimpleDateFormat(format).format(time);
} catch (Exception e) {
result = "";
LogUtil.e("时间转换错误:" + e.getMessage());
} finally {
return result;
}
}
public static String getLoveDay(long time) {
String result = "";
Calendar calendar = getCalendar();
calendar.setTimeInMillis(time);
int loveDay = calendar.get(Calendar.DAY_OF_MONTH);
int loveMonth = calendar.get(Calendar.MONTH);
int loveYear = calendar.get(Calendar.YEAR);
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
if (loveDay == calendar.get(Calendar.DAY_OF_MONTH)) {
result = ((calendar.get(Calendar.YEAR) - loveYear) * 12 + (calendar.get(Calendar.MONTH) - loveMonth)) + " 个月";
} else {
long diff = (calendar.getTimeInMillis() - time) / 1000 / 60 / 60 / 24;
result = diff + " 天";
}
return result;
}
public static int getDay(long time) {
Calendar calendar = getCalendar();
calendar.setTimeInMillis(time);
return calendar.get(Calendar.DAY_OF_MONTH);
}
public static String getWeek(long currentTime) {
calendar.setTimeInMillis(currentTime);
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
switch (calendar.get(Calendar.DAY_OF_WEEK)) {
case Calendar.MONDAY:
return "周一";
case Calendar.TUESDAY:
return "周二";
case Calendar.WEDNESDAY:
return "周三";
case Calendar.THURSDAY:
return "周四";
case Calendar.FRIDAY:
return "周五";
case Calendar.SATURDAY:
return "周六";
case Calendar.SUNDAY:
return "周日";
default:
return "";
}
}
}
| 29.123077 | 122 | 0.548072 |
00a3665e34df203ec9b275a49acea6b78dbdcb8c | 1,082 | package br.skylight.commons.dli.vehicle;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import br.skylight.commons.dli.services.Message;
import br.skylight.commons.dli.services.MessageType;
public class VehicleConfigurationCommand extends Message<VehicleConfigurationCommand> {
private float initialPropulsionEnergy;
public float getInitialPropulsionEnergy() {
return initialPropulsionEnergy;
}
public void setInitialPropulsionEnergy(float initialPropulsionEnergy) {
this.initialPropulsionEnergy = initialPropulsionEnergy;
}
@Override
public void readState(DataInputStream in) throws IOException {
super.readState(in);
initialPropulsionEnergy = in.readFloat();
}
@Override
public void writeState(DataOutputStream out) throws IOException {
super.writeState(out);
out.writeFloat(initialPropulsionEnergy);
}
@Override
public MessageType getMessageType() {
return MessageType.M40;
}
@Override
public void resetValues() {
initialPropulsionEnergy = 0;
}
}
| 25.761905 | 88 | 0.769871 |
a14ecbe7f7799e49a016318c642901e06dc62b7a | 226 | package gui;
import java.awt.Point;
public interface Selectable {
public boolean isSelected();
public void select(Selection s);
public void deselect();
public Point getLocation();
public void moveTo(int x, int y);
}
| 16.142857 | 34 | 0.734513 |
3d6c443fd2d37df63d2d7f4880d7081e62376dcf | 7,222 | /*
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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.apache.batchee.container.services.transaction;
import org.apache.batchee.container.exception.TransactionManagementException;
import org.apache.batchee.spi.TransactionManagerAdapter;
import javax.naming.InitialContext;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.InvalidTransactionException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
public class JTAUserTransactionAdapter implements TransactionManagerAdapter {
private static final String[] JNDI_LOCS = new String[] { // taken from OpenJPA ManagedRuntime
"java:comp/TransactionManager", // generic, TomEE
"javax.transaction.TransactionManager", // weblogic
"java:/TransactionManager", // jboss, jrun, Geronimo
"java:/DefaultDomain/TransactionManager", // jrun too
"java:comp/pm/TransactionManager", // orion & oracle
"java:appserver/TransactionManager", // GlassFish
"java:pm/TransactionManager", // borland
"aries:services/javax.transaction.TransactionManager", // Apache Aries
};
private static final String[] METHODS = new String[] { // taken from OpenJPA ManagedRuntime
"org.openejb.OpenEJB.getTransactionManager",
"com.arjuna.jta.JTA_TransactionManager.transactionManager", // hp
"com.bluestone.jta.SaTransactionManagerFactory.SaGetTransactionManager",
"com.sun.jts.jta.TransactionManagerImpl.getTransactionManagerImpl",
"com.inprise.visitransact.jta.TransactionManagerImpl.getTransactionManagerImpl", // borland
"com.ibm.tx.jta.TransactionManagerFactory.getTransactionManager" // IBM WebSphere 8
};
protected TransactionManager mgr = null;
public JTAUserTransactionAdapter() {
for (final String jndiLoc : JNDI_LOCS) {
try {
mgr = TransactionManager.class.cast(new InitialContext().lookup(jndiLoc));
} catch (final Throwable t) {
// no-op
}
if (mgr != null) {
break;
}
}
if (mgr == null) {
for (final String method : METHODS) {
final String clazz = method.substring(0, method.lastIndexOf('.'));
final String methodName = method.substring(method.lastIndexOf('.') + 1);
try {
mgr = TransactionManager.class.cast(
Thread.currentThread().getContextClassLoader().loadClass(clazz).getMethod(methodName).invoke(null));
if (mgr != null) {
break;
}
} catch (final Throwable e) {
// no-op
}
}
}
if (mgr == null) {
throw new TransactionManagementException("no transaction manager found");
}
}
@Override
public void begin() throws TransactionManagementException {
try {
mgr.begin();
} catch (final NotSupportedException e) {
throw new TransactionManagementException(e);
} catch (final SystemException e) {
throw new TransactionManagementException(e);
}
}
public Transaction beginSuspending() throws TransactionManagementException {
try {
final Transaction t = mgr.getTransaction() != null ? mgr.suspend() : null;
mgr.begin();
return t;
} catch (final NotSupportedException e) {
throw new TransactionManagementException(e);
} catch (final SystemException e) {
throw new TransactionManagementException(e);
}
}
public void resume(final Transaction transaction) {
try {
mgr.resume(transaction);
} catch (final InvalidTransactionException e) {
throw new TransactionManagementException(e);
} catch (final SystemException e) {
throw new TransactionManagementException(e);
}
}
@Override
public void commit() throws TransactionManagementException {
try {
mgr.commit();
} catch (final SecurityException e) {
throw new TransactionManagementException(e);
} catch (final IllegalStateException e) {
throw new TransactionManagementException(e);
} catch (final RollbackException e) {
throw new TransactionManagementException(e);
} catch (final HeuristicMixedException e) {
throw new TransactionManagementException(e);
} catch (final HeuristicRollbackException e) {
throw new TransactionManagementException(e);
} catch (final SystemException e) {
throw new TransactionManagementException(e);
}
}
@Override
public void rollback() throws TransactionManagementException {
try {
mgr.rollback();
} catch (final IllegalStateException e) {
throw new TransactionManagementException(e);
} catch (final SecurityException e) {
throw new TransactionManagementException(e);
} catch (final SystemException e) {
throw new TransactionManagementException(e);
}
}
@Override
public int getStatus() throws TransactionManagementException {
try {
return mgr.getStatus();
} catch (final SystemException e) {
throw new TransactionManagementException(e);
}
}
@Override
public void setRollbackOnly() throws TransactionManagementException {
try {
mgr.setRollbackOnly();
} catch (final IllegalStateException e) {
throw new TransactionManagementException(e);
} catch (final SystemException e) {
throw new TransactionManagementException(e);
}
}
@Override
public void setTransactionTimeout(final int seconds) throws TransactionManagementException {
try {
mgr.setTransactionTimeout(seconds);
} catch (final SystemException e) {
throw new TransactionManagementException(e);
}
}
}
| 40.346369 | 125 | 0.633758 |
c2d533c535b770a0bd91208f0b357cb467198e28 | 7,527 | package org.sagebionetworks.bridge.fitbit.schema;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.sagebionetworks.repo.model.table.ColumnType;
import org.testng.annotations.Test;
import org.sagebionetworks.bridge.json.DefaultObjectMapper;
public class EndpointSchemaTest {
private static final String ENDPOINT_ID = "test-endpoint";
private static final Set<String> IGNORED_KEYS = ImmutableSet.of("ignore-asdf", "ignore-jkl;");
private static final String SCOPE_NAME = "DUMMY_SCOPE";
private static final String URL = "http://example.com/";
private static final List<UrlParameterType> URL_PARAMETERS = ImmutableList.of(UrlParameterType.DATE,
UrlParameterType.USER_ID);
private static final ColumnSchema FOO_COLUMN_SCHEMA = new ColumnSchema.Builder().withColumnId("foo-column")
.withColumnType(ColumnType.INTEGER).build();
private static final TableSchema FOO_TABLE_SCHEMA = new TableSchema.Builder().withTableKey("foo-table")
.withColumns(ImmutableList.of(FOO_COLUMN_SCHEMA)).build();
private static final ColumnSchema BAR_COLUMN_SCHEMA = new ColumnSchema.Builder().withColumnId("bar-column")
.withColumnType(ColumnType.INTEGER).build();
private static final TableSchema BAR_TABLE_SCHEMA = new TableSchema.Builder().withTableKey("bar-table")
.withColumns(ImmutableList.of(BAR_COLUMN_SCHEMA)).build();
private static final List<TableSchema> TABLE_SCHEMA_LIST = ImmutableList.of(FOO_TABLE_SCHEMA, BAR_TABLE_SCHEMA);
@Test
public void success() {
EndpointSchema endpointSchema = makeValidBuilder().build();
assertEquals(endpointSchema.getEndpointId(), ENDPOINT_ID);
assertTrue(endpointSchema.getIgnoredKeys().isEmpty());
assertEquals(endpointSchema.getScopeName(), SCOPE_NAME);
assertEquals(endpointSchema.getUrl(), URL);
assertTrue(endpointSchema.getUrlParameters().isEmpty());
assertEquals(endpointSchema.getTables(), TABLE_SCHEMA_LIST);
Map<String, TableSchema> tablesByKey = endpointSchema.getTablesByKey();
assertEquals(tablesByKey.size(), 2);
assertEquals(tablesByKey.get(FOO_TABLE_SCHEMA.getTableKey()), FOO_TABLE_SCHEMA);
assertEquals(tablesByKey.get(BAR_TABLE_SCHEMA.getTableKey()), BAR_TABLE_SCHEMA);
}
@Test
public void optionalParams() {
EndpointSchema endpointSchema = makeValidBuilder().withIgnoredKeys(IGNORED_KEYS)
.withUrlParameters(URL_PARAMETERS).build();
assertEquals(endpointSchema.getEndpointId(), ENDPOINT_ID);
assertEquals(endpointSchema.getIgnoredKeys(), IGNORED_KEYS);
assertEquals(endpointSchema.getUrl(), URL);
assertEquals(endpointSchema.getUrlParameters(), URL_PARAMETERS);
assertEquals(endpointSchema.getTables(), TABLE_SCHEMA_LIST);
// tablesByKey is already tested above. Just test that it exists.
assertNotNull(endpointSchema.getTablesByKey());
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"endpointId must be specified")
public void nullEndpointId() {
makeValidBuilder().withEndpointId(null).build();
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"endpointId must be specified")
public void emptyEndpointId() {
makeValidBuilder().withEndpointId("").build();
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"endpointId must be specified")
public void blankEndpointId() {
makeValidBuilder().withEndpointId(" ").build();
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"scopeName must be specified")
public void nullScopeName() {
makeValidBuilder().withScopeName(null).build();
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"scopeName must be specified")
public void emptyScopeName() {
makeValidBuilder().withScopeName("").build();
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"scopeName must be specified")
public void blankScopeName() {
makeValidBuilder().withScopeName(" ").build();
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"url must be specified")
public void nullUrl() {
makeValidBuilder().withUrl(null).build();
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"url must be specified")
public void emptyUrl() {
makeValidBuilder().withUrl("").build();
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"url must be specified")
public void blankUrl() {
makeValidBuilder().withUrl(" ").build();
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"tables must be non-null and non-empty")
public void nullTables() {
makeValidBuilder().withTables(null).build();
}
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp =
"tables must be non-null and non-empty")
public void emptyTables() {
makeValidBuilder().withTables(ImmutableList.of()).build();
}
@Test
public void deserialization() throws Exception {
// We only ever deserialize, never serialize.
// Serialization of TableSchema is tested in TableSchemaTest. For this test, just use the serialized value of
// a TableSchema so we don't have to worry about testing it twice.
// Start with JSON
String jsonText = "{\n" +
" \"endpointId\":\"" + ENDPOINT_ID + "\",\n" +
" \"ignoredKeys\":[\"ignore-asdf\", \"ignore-jkl;\"],\n" +
" \"scopeName\":\"" + SCOPE_NAME + "\",\n" +
" \"url\":\"" + URL + "\",\n" +
" \"urlParameters\":[\"DATE\", \"USER_ID\"],\n" +
" \"tables\":" + DefaultObjectMapper.INSTANCE.writeValueAsString(TABLE_SCHEMA_LIST) + "\n" +
"}";
// Convert to POJO
EndpointSchema endpointSchema = DefaultObjectMapper.INSTANCE.readValue(jsonText, EndpointSchema.class);
assertEquals(endpointSchema.getEndpointId(), ENDPOINT_ID);
assertEquals(endpointSchema.getIgnoredKeys(), IGNORED_KEYS);
assertEquals(endpointSchema.getScopeName(), SCOPE_NAME);
assertEquals(endpointSchema.getUrl(), URL);
assertEquals(endpointSchema.getUrlParameters(), URL_PARAMETERS);
assertEquals(endpointSchema.getTables(), TABLE_SCHEMA_LIST);
// tablesByKey is already tested above. Just test that it exists.
assertNotNull(endpointSchema.getTablesByKey());
}
private static EndpointSchema.Builder makeValidBuilder() {
return new EndpointSchema.Builder().withEndpointId(ENDPOINT_ID).withUrl(URL).withScopeName(SCOPE_NAME)
.withTables(TABLE_SCHEMA_LIST);
}
}
| 45.343373 | 117 | 0.698153 |
1b6fccaea91eddb6a6406e44421010579a49af7f | 2,681 | package tv.dyndns.kishibe.qmaclone.client.ranking;
import java.util.List;
import tv.dyndns.kishibe.qmaclone.client.packet.PacketRankingData;
import tv.dyndns.kishibe.qmaclone.client.report.SafeHtmlColumn;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.safehtml.shared.SafeUri;
import com.google.gwt.safehtml.shared.UriUtils;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.ProvidesKey;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
public class CellTableRanking extends CellTable<PacketRankingData> {
interface Factory {
CellTableRanking create(String dataLabel);
}
interface CellTableRankingTemplates extends SafeHtmlTemplates {
@Template("<img src=\"{0}\" style=\"width: 48px; height: 48px;\">")
SafeHtml icon(SafeUri fileName);
}
private static final CellTableRankingTemplates TEMPLATES = GWT
.create(CellTableRankingTemplates.class);
private final ListDataProvider<PacketRankingData> rankingProvider = new ListDataProvider<PacketRankingData>();
@Inject
public CellTableRanking(@Assisted String dataLabel) {
super(0, GWT.<CellTable.BasicResources> create(CellTable.BasicResources.class),
new ProvidesKey<PacketRankingData>() {
@Override
public Object getKey(PacketRankingData item) {
return item.imageFileName;
}
});
rankingProvider.addDataDisplay(this);
// 順位
addColumn(new SafeHtmlColumn<PacketRankingData>() {
@Override
public SafeHtml getValue(PacketRankingData object) {
return SafeHtmlUtils.fromString(String.valueOf(object.ranking));
}
}, "順位");
// アイコン
addColumn(new SafeHtmlColumn<PacketRankingData>() {
@Override
public SafeHtml getValue(PacketRankingData object) {
return TEMPLATES.icon(UriUtils.fromString("http://kishibe.dyndns.tv/qmaclone/icon/"
+ object.imageFileName));
}
}, "");
// プレイヤー
addColumn(new SafeHtmlColumn<PacketRankingData>() {
@Override
public SafeHtml getValue(PacketRankingData object) {
return SafeHtmlUtils.fromString(object.name);
}
}, "プレイヤー");
// データ
addColumn(new SafeHtmlColumn<PacketRankingData>() {
@Override
public SafeHtml getValue(PacketRankingData object) {
return SafeHtmlUtils.fromString(object.data);
}
}, dataLabel);
}
public void setRanking(List<PacketRankingData> ranking) {
setPageSize(ranking.size());
rankingProvider.setList(ranking);
rankingProvider.refresh();
}
}
| 30.123596 | 111 | 0.763148 |
705e47faae044bddc7508416b6a5902853a1cd25 | 34,337 | /**
* Copyright © 2015, University of Washington
* 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 the University of Washington 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 UNIVERSITY OF
* WASHINGTON BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package edu.uw.apl.tupelo.shell;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.LinkedList;
import java.util.UUID;
import org.apache.commons.cli.*;
import org.apache.commons.codec.binary.Hex;
import edu.uw.apl.commons.shell.Shell;
import edu.uw.apl.commons.tsk4j.image.Image;
import edu.uw.apl.commons.tsk4j.volsys.Partition;
import edu.uw.apl.commons.tsk4j.volsys.VolumeSystem;
import edu.uw.apl.commons.tsk4j.digests.BodyFile;
import edu.uw.apl.commons.tsk4j.digests.BodyFile.Record;
import edu.uw.apl.commons.tsk4j.digests.BodyFileBuilder.BuilderCallback;
import edu.uw.apl.commons.tsk4j.digests.VolumeSystemHash;
import edu.uw.apl.commons.tsk4j.digests.VolumeSystemHashCodec;
import edu.uw.apl.commons.tsk4j.filesys.FileSystem;
import edu.uw.apl.vmvols.model.VirtualMachine;
import edu.uw.apl.vmvols.fuse.VirtualMachineFileSystem;
import edu.uw.apl.tupelo.model.Session;
import edu.uw.apl.tupelo.model.ManagedDisk;
import edu.uw.apl.tupelo.model.ManagedDiskDescriptor;
import edu.uw.apl.tupelo.model.ManagedDiskDigest;
import edu.uw.apl.tupelo.model.DiskImage;
import edu.uw.apl.tupelo.model.FlatDisk;
import edu.uw.apl.tupelo.model.physical.PhysicalDisk;
import edu.uw.apl.tupelo.model.virtual.VirtualDisk;
import edu.uw.apl.tupelo.model.ProgressMonitor;
import edu.uw.apl.tupelo.model.StreamOptimizedDisk;
import edu.uw.apl.tupelo.model.UnmanagedDisk;
import edu.uw.apl.tupelo.http.client.HttpStoreProxy;
import edu.uw.apl.tupelo.store.Store;
import edu.uw.apl.tupelo.store.null_.NullStore;
import edu.uw.apl.tupelo.utils.Discovery;
import edu.uw.apl.tupelo.utils.DiskHashUtils;
import edu.uw.apl.tupelo.store.filesys.FilesystemStore;
/**
* A cmd line shell for the Tupelo system. Works along the lines of
* bash...
*/
public class Elvis extends Shell {
private String storeLocation;
private Store store;
private List<PhysicalDisk> physicalDisks;
private List<VirtualDisk> virtualDisks;
private List<DiskImage> diskImages;
private static boolean verbose, debug;
private Session session;
private VirtualMachineFileSystem vmfs;
// Bodyfiles for unmanaged disks
// This is only hashes done this session
private Map<UnmanagedDisk, List<BodyFile>> diskFileRecords;
/**
* Path to check for potential disks
*/
static public final String[] PHYSICAL_DISK_NAMES = {
// Linux/Unix...
"/dev/sda", "/dev/sdb", "/dev/sdc",
"/dev/sdd", "/dev/sde", "/dev/sdf",
"/dev/sdg", "/dev/sdh", "/dev/sdi",
// MacOS...
"/dev/disk0", "/dev/disk1", "/dev/disk2",
"/dev/disk3", "/dev/disk4", "/dev/disk5"
};
private static final String UNMANAGED_DISK_REPORT_FORMAT = "%2s %42s %16s %16s";
private static final String MANAGED_DISK_REPORT_FORMAT = "%2s %42s %17s";
private static final String ATTRIBUTE_REPORT_FORMAT = "%2s %42s";
/**
* Property name for defining the Tupelo store location
*/
public static final String STORE_PROPERTY = "store-location";
static public void main( String[] args ) {
try {
Elvis main = new Elvis();
main.readConfig();
main.readArgs( args );
main.start();
main.finish();
System.exit(0);
} catch( Exception e ) {
e.printStackTrace();
System.exit(-1);
}
}
public Elvis() {
super();
physicalDisks = new ArrayList<PhysicalDisk>();
virtualDisks = new ArrayList<VirtualDisk>();
diskImages = new ArrayList<DiskImage>();
diskFileRecords = new HashMap<UnmanagedDisk, List<BodyFile>>();
// Try and load the store location via the Discovery class
storeLocation = Discovery.locatePropertyValue(STORE_PROPERTY);
if(storeLocation == null){
// Use the default if not defined
storeLocation = "./test-store";
}
verbose = false;
// report available Java memory...
addCommand( "mem", new Lambda() {
public void apply( String[] args ) throws Exception {
Runtime rt = Runtime.getRuntime();
long mem = rt.freeMemory();
System.out.println( "Free Memory: " + mem );
}
} );
commandHelp( "mem", "Print free memory" );
// report store-managed data...
addCommand( "ms", new Lambda() {
public void apply( String[] args ) throws Exception {
Collection<ManagedDiskDescriptor> mdds = store.enumerate();
reportManagedDisks( mdds );
}
} );
commandHelp( "ms", "List store-managed disks" );
// report store's free disk space...
addCommand( "space", new Lambda() {
public void apply( String[] args ) throws Exception {
long usableSpace = store.getUsableSpace();
System.out.println( "Usable space: " + usableSpace );
}
} );
commandHelp( "space", "Print store's free disk space" );
// report unmanaged data...
addCommand( "us", new Lambda() {
public void apply( String[] args ) throws Exception {
reportUnmanagedDisks();
}
} );
commandHelp( "us", "List local unmanaged disks" );
// report the store url...
addCommand( "s", new Lambda() {
public void apply( String[] args ) throws Exception {
System.out.println( "Store: " + storeLocation );
}
} );
commandHelp( "s", "Print the store location" );
/*
vshash, hash the volume system (unallocated areas) of an identified
unmanaged disk
*/
addCommand( "vshash", "(.+)", new Lambda() {
public void apply( String[] args ) throws Exception {
String needle = args[1];
needle = needle.trim();
UnmanagedDisk ud = null;
try {
ud = locateUnmanagedDisk( needle );
} catch( IndexOutOfBoundsException oob ) {
System.err.println
( "No unmanaged disk " + needle +
". Use 'us' to list unmanaged disks" );
return;
}
if( ud == null ) {
System.out.println( "No unmanaged disk: " +
needle );
return;
}
hashVolumeSystem( ud );
}
} );
commandHelp( "vshash", "unmanagedDisk",
"Hash each unallocated area of the identified unmanaged disk, storing the result as a managed disk attribute" );
addCommand("fshash", "(.+)", new Lambda() {
public void apply(String args[]) throws Exception {
String diskName = args[1].trim();
UnmanagedDisk ud = null;
try {
ud = locateUnmanagedDisk(diskName);
} catch (IndexOutOfBoundsException oob) {
System.err.println("No unmanaged disk " + diskName + ". Use 'us' to list unmanaged disks");
return;
}
if (ud == null) {
System.out.println("No unmanaged disk: " + diskName);
return;
}
// Prep the session
checkSession();
DiskHashUtils disk = null;
try {
Date start = new Date();
if(ud instanceof VirtualDisk){
VirtualDisk vDisk = (VirtualDisk) ud;
// Virtual disk, this takes extra steps to set up
// Set up the virtual machine FS mount point
checkVMFS();
// Get and mount the VM
VirtualMachine vm = vDisk.getVM();
vmfs.add(vm);
File diskPath = vmfs.pathTo(vDisk.getDelegate());
// Create the disk
disk = new DiskHashUtils(diskPath.getAbsolutePath());
} else {
disk = new DiskHashUtils(ud.getSource().getAbsolutePath());
}
List<BodyFile> bodyFiles = new LinkedList<BodyFile>();
// Process each parition individually
List<Partition> partitions = disk.getPartitions();
if (partitions != null) {
for (Partition partition : partitions) {
// Make sure there is a filesystem
FileSystem fs = disk.getFileSystem(partition);
if (fs == null) {
continue;
}
// Callback, for printing status
final BuilderCallback callback = new BuilderCallback() {
private int totalFiles = 0;
@Override
public int getUpdateInterval() {
return 1000;
}
@Override
public void gotRecords(List<Record> records) {
totalFiles += records.size();
System.out.println("Processed "+totalFiles+" files");
}
};
BodyFile bodyFile = disk.hashFileSystem(fs, callback);
bodyFiles.add(bodyFile);
// Write the data
writeRecordData(bodyFile, diskName + "-" + session + "-" + partition.start() + "-"
+ partition.length() + ".bodyfile");
}
} else {
FileSystem fs = disk.getFileSystem();
if (fs == null) {
System.err.println("No filesystem found");
disk.close();
return;
}
BodyFile bodyFile = disk.hashFileSystem(fs);
bodyFiles.add(bodyFile);
// Write the bodyfile
writeRecordData(bodyFile, diskName + "-" + session + ".bodyfile");
}
disk.close();
// Store it for now
diskFileRecords.put(ud, bodyFiles);
Date end = new Date();
System.out.println("Elapsed time: " + (end.getTime() - start.getTime()) / 1000 + "sec");
} catch (Exception e) {
log.warn(e);
if (debug) {
e.printStackTrace();
}
} finally {
// Always try and close the disk
try{
disk.close();
} catch(Exception e){
// Ignore
}
}
}
});
commandHelp("fshash", "unmanagedDisk",
"Hash each filesystem of the identified unmanaged disk. The resulting bodyfiles are written to the current directory, and will also be sent to the store if the disk is.");
// putdisk, xfer an unmanaged disk to the store
addCommand( "putdisk", "(.+)", new Lambda() {
public void apply( String[] args ) throws Exception {
String needle = args[1];
UnmanagedDisk ud = null;
try {
ud = locateUnmanagedDisk( needle );
} catch( IndexOutOfBoundsException oob ) {
System.err.println
( "No unmanaged disk " + needle +
". Use 'us' to list unmanaged disks" );
return;
}
if( ud == null ) {
System.out.println( "No unmanaged disk: " +
needle );
return;
}
try {
putDisk( ud );
} catch( IOException ioe ) {
log.warn( ioe );
System.err.println( "" + ioe );
}
}
} );
commandHelp( "putdisk", "unmanagedDiskPath|unmanagedDiskIndex",
"Transfer an identified unmanaged disk to the store" );
// list attributes for a given managed disk
addCommand( "as", "(.+)", new Lambda() {
public void apply( String[] args ) throws Exception {
String needle = args[1];
ManagedDiskDescriptor mdd = null;
try {
mdd = locateManagedDisk( needle );
} catch( RuntimeException iae ) {
System.err.println( iae );
return;
}
if( mdd == null ) {
System.out.println( "No managed disk: " +
needle );
return;
}
try {
listAttributes( mdd );
} catch( IOException ioe ) {
log.warn( ioe );
System.err.println( "" + ioe );
}
}
} );
commandHelp( "as", "managedDiskIndex",
"List attributes of an identified managed disk" );
addCommand("findmd5", "(.+)", new Lambda() {
@Override
public void apply(String[] args) throws Exception {
checkForHashes("MD5", args);
}
});
commandHelp("findmd5", "MD5 hashes",
"Check all managed disks to see which ones contain the specified MD5 file hash(es). "+
"Seperate multiple hashes by a space.");
addCommand("findsha1", "(.+)", new Lambda() {
@Override
public void apply(String[] args) throws Exception {
checkForHashes("SHA1", args);
}
});
commandHelp("findsha1", "SHA1 hashes",
"Check all managed disks to see which ones contain the specified SHA1 file hash(es). "+
"Seperate multiple hashes by a space.");
addCommand("findsha256", "(.+)", new Lambda() {
@Override
public void apply(String[] args) throws Exception {
checkForHashes("SHA256", args);
}
});
commandHelp("findsha256", "SHA256 hashes",
"Check all managed disks to see which ones contain the specified SHA256 file hash(es). "+
"Seperate multiple hashes by a space.");
}
/**
* Run a check for hashes of a specific type
* @param algorithm
* @param args the hashes, in hex
*/
private void checkForHashes(String algorithm, String[] args){
try {
// Get and verify the hashes
String input = args[0];
String[] hashes = input.split("\\s+");
// Check which managed disks have file hash data
Collection<ManagedDiskDescriptor> disks = store.enumerate();
for (ManagedDiskDescriptor mdd : disks) {
// Let the user know which disks are missing file hash
// data
if (!store.hasFileRecords(mdd)) {
System.out.println("Warning: disk is missing file hash data: " + mdd);
}
}
// Build the list of hashes in bytes
List<byte[]> byteHashes = new ArrayList<byte[]>(hashes.length);
for (String hash : hashes) {
byteHashes.add(Hex.decodeHex(hash.toCharArray()));
}
// Start looking for the hashes
List<ManagedDiskDescriptor> matchingDisks = store.checkForHashes(algorithm, byteHashes);
// Report our results
if(matchingDisks.isEmpty()){
System.out.println("Hash not found.");
} else {
System.out.println("Hash found on the following disks:");
for(ManagedDiskDescriptor mdd : matchingDisks){
System.out.println(mdd.toString());
System.out.println("Matching MD5|SHA1|SHA256|Size|Path:");
List<Record> records = store.getRecords(mdd, algorithm, byteHashes);
for(Record record : records){
String md5 = new String(Hex.encodeHex(record.md5));
String sha1 = new String(Hex.encodeHex(record.sha1));
String sha256 = new String(Hex.encodeHex(record.sha256));
System.out.println(md5+"|"+sha1+"|"+sha256+"|"+record.size+"|"+record.path);
}
System.out.println("\n");
}
}
} catch (Exception e) {
log.warn(e);
System.out.println("" + e);
}
}
static protected void printUsage( Options os, String usage,
String header, String footer ) {
HelpFormatter hf = new HelpFormatter();
hf.setWidth( 80 );
hf.printHelp( usage, header, os, footer );
}
public void readArgs( String[] args ) throws Exception {
Options os = new Options();
os.addOption( "c", true, "command string" );
os.addOption( "d", false, "debug" );
os.addOption( "s", true, "store location (file/http)" );
os.addOption( "u", true, "path to unmanaged disk" );
os.addOption( "V", false, "show version number and exit" );
String USAGE = Elvis.class.getName() + " [-c] [-d] [-s] [-u] [-V]";
final String HEADER = "";
final String FOOTER = "";
CommandLineParser clp = new DefaultParser();
CommandLine cl = null;
try {
cl = clp.parse( os, args );
} catch( Exception e ) {
printUsage( os, USAGE, HEADER, FOOTER );
System.exit(1);
}
debug = cl.hasOption( "d" );
if( cl.hasOption( "s" ) ) {
storeLocation = cl.getOptionValue( "s" );
}
if( cl.hasOption( "c" ) ) {
cmdString = cl.getOptionValue( "c" );
}
if( cl.hasOption( "u" ) ) {
String[] ss = cl.getOptionValues( "u" );
for( String s : ss ) {
File f = new File( s );
if( !( f.canRead() ) )
continue;
if( VirtualDisk.likelyVirtualDisk( f ) ) {
VirtualDisk vd = new VirtualDisk( f );
virtualDisks.add( vd );
} else {
DiskImage di = new DiskImage( f );
diskImages.add( di );
}
}
}
if( cl.hasOption( "V" ) ) {
Package p = getClass().getPackage();
String version = p.getImplementationVersion();
System.out.println( p.getName() + "/" + version );
System.exit(0);
}
args = cl.getArgs();
if( args.length > 0 ) {
cmdFile = new File( args[0] );
if( !cmdFile.exists() ) {
// like bash would do, write to stderr...
System.err.println( cmdFile + ": No such file or directory" );
System.exit(-1);
}
}
}
@Override
public void start() throws Exception {
try {
store = buildStore();
} catch( IllegalStateException ise ) {
System.err.println( "Cannot locate store: '" + storeLocation +
"'." );
System.err.println( "For a file-based store, first 'mkdir " +
storeLocation + "'" );
System.exit(1);
}
report( "Store: " + storeLocation );
identifyUnmanagedDisks();
super.start();
}
private void listAttributes( ManagedDiskDescriptor mdd ) throws IOException{
Collection<String> attrNames = store.listAttributes( mdd );
reportAttributes( attrNames );
}
private UnmanagedDisk locateUnmanagedDisk( String needle ) {
try {
int i = Integer.parseInt( needle );
return locateUnmanagedDisk( i );
} catch( NumberFormatException nfe ) {
// proceed with name-based lookup...
}
for( PhysicalDisk pd : physicalDisks ) {
String s = pd.getSource().getPath();
if( s.startsWith( needle ) )
return pd;
}
for( VirtualDisk vd : virtualDisks ) {
String s = vd.getSource().getName();
if( s.startsWith( needle ) )
return vd;
}
for( DiskImage di : diskImages ) {
String s = di.getSource().getName();
if( s.startsWith( needle ) )
return di;
}
return null;
}
/**
* 1-based search, natural numbers
*/
private UnmanagedDisk locateUnmanagedDisk( int needle ) {
int total = physicalDisks.size() + virtualDisks.size() +
diskImages.size();
if( needle < 1 || needle > total )
throw new IndexOutOfBoundsException( "Index out-of-range: " +
needle );
needle--;
if( needle < physicalDisks.size() )
return physicalDisks.get( needle );
needle -= physicalDisks.size();
if( needle < virtualDisks.size() )
return virtualDisks.get( needle );
needle -= virtualDisks.size();
if( needle < diskImages.size() )
return diskImages.get( needle );
// should never occur given earlier bounds check
return null;
}
private ManagedDiskDescriptor locateManagedDisk( String needle )
throws IOException {
try {
int i = Integer.parseInt( needle );
return locateManagedDisk( i );
} catch( NumberFormatException nfe ) {
// proceed with name-based lookup...
}
// TODO
return null;
}
private ManagedDiskDescriptor locateManagedDisk( int index )
throws IOException {
Collection<ManagedDiskDescriptor> mdds = store.enumerate();
List<ManagedDiskDescriptor> sorted =
new ArrayList<ManagedDiskDescriptor>( mdds );
Collections.sort( sorted, ManagedDiskDescriptor.DEFAULTCOMPARATOR );
int total = sorted.size();
if( index < 1 || index > total )
throw new IllegalArgumentException( "Index out-of-range: " +
index );
return sorted.get(index-1);
}
private void identifyUnmanagedDisks() {
identifyPhysicalDisks();
}
private void identifyPhysicalDisks() {
for( String pdName : PHYSICAL_DISK_NAMES ) {
File pdf = new File( pdName );
if( !pdf.exists() )
continue;
if( !pdf.canRead() ) {
if( isInteractive() ) {
System.out.println( "Unreadable: " + pdf );
continue;
}
}
try {
PhysicalDisk pd = new PhysicalDisk( pdf );
log.info( "Located " + pdf );
physicalDisks.add( pd );
} catch( IOException ioe ) {
log.error( ioe );
}
}
}
private void finish() throws Exception {
if( isInteractive() ){
System.out.println( "Bye!" );
}
if(vmfs != null){
try{
vmfs.umount();
} catch(Exception e){
// Ignore it
}
}
}
private void report( String msg ) {
if( !isInteractive() )
return;
System.out.println( msg );
}
private Store buildStore() {
Store store = null;
if( storeLocation.equals( "/dev/null" ) ) {
store = new NullStore();
} else if( storeLocation.startsWith( "http" ) ) {
HttpStoreProxy proxy = new HttpStoreProxy(storeLocation);
// Check the store version
String version = getClass().getPackage().getImplementationVersion();
if(version != null){
try {
String serverVersion = proxy.getServerVersion();
// Warn the user if the version is different
if(!version.equals(serverVersion)){
System.err.println("----");
System.err.println("WARNING: Server version is different than client");
System.err.println("Client version: "+version);
System.err.println("Server version: "+serverVersion);
System.err.println("----");
}
} catch (IOException e) {
System.err.println("Error checking the server's version: "+e);
log.error("Exception checking the server's version", e);
}
}
store = proxy;
} else {
File dir = new File( storeLocation );
if( !dir.isDirectory() ) {
throw new IllegalStateException
( "Not a directory: " + storeLocation );
}
store = new FilesystemStore( dir );
}
return store;
}
@Override
protected void prompt() {
System.out.print( "tupelo> " );
System.out.flush();
}
void reportManagedDisks( Collection<ManagedDiskDescriptor> mdds ) {
String header = String.format( MANAGED_DISK_REPORT_FORMAT,
"N", "ID", "Session" );
System.out.println( header );
int n = 1;
List<ManagedDiskDescriptor> sorted =
new ArrayList<ManagedDiskDescriptor>( mdds );
Collections.sort( sorted, ManagedDiskDescriptor.DEFAULTCOMPARATOR );
for( ManagedDiskDescriptor mdd : sorted ) {
String fmt = String.format( MANAGED_DISK_REPORT_FORMAT, n,
mdd.getDiskID(),
mdd.getSession() );
System.out.println( fmt );
n++;
}
}
void reportAttributes( Collection<String> attrNames ) {
String header = String.format( ATTRIBUTE_REPORT_FORMAT,
"N", "Name" );
System.out.println( header );
int n = 1;
List<String> sorted = new ArrayList<String>( attrNames );
Collections.sort( sorted );
for( String s : sorted ) {
String fmt = String.format( ATTRIBUTE_REPORT_FORMAT, n, s );
System.out.println( fmt );
n++;
}
}
void reportUnmanagedDisks() {
String header = String.format( UNMANAGED_DISK_REPORT_FORMAT,
"N", "ID", "Size", "Path" );
System.out.println( header );
reportPhysicalDisks( 1 );
reportVirtualDisks( 1 + physicalDisks.size() );
reportDiskImages( 1 + physicalDisks.size() + virtualDisks.size() );
}
void reportPhysicalDisks( int n ) {
for( PhysicalDisk pd : physicalDisks ) {
String fmt = String.format( UNMANAGED_DISK_REPORT_FORMAT,
n, pd.getID(), pd.size(),
pd.getSource() );
System.out.println( fmt );
n++;
}
}
void reportVirtualDisks( int n ) {
for( VirtualDisk vd : virtualDisks ) {
String fmt = String.format( UNMANAGED_DISK_REPORT_FORMAT,
n, vd.getID(), vd.size(),
vd.getSource().getName() );
System.out.println( fmt );
n++;
}
}
void reportDiskImages( int n ) {
for( DiskImage di : diskImages ) {
String fmt = String.format( UNMANAGED_DISK_REPORT_FORMAT,
n, di.getID(), di.size(),
di.getSource().getName() );
System.out.println( fmt );
n++;
}
}
private void checkSession() throws IOException {
if( session == null ) {
session = store.newSession();
report( "Session: " + session );
}
}
private void putDisk( UnmanagedDisk ud ) throws IOException {
checkSession();
Collection<ManagedDiskDescriptor> existing = store.enumerate();
if( verbose )
System.out.println( "Stored data: " + existing );
List<ManagedDiskDescriptor> matching =
new ArrayList<ManagedDiskDescriptor>();
for( ManagedDiskDescriptor mdd : existing ) {
if( mdd.getDiskID().equals( ud.getID() ) ) {
matching.add( mdd );
}
}
Collections.sort( matching, ManagedDiskDescriptor.DEFAULTCOMPARATOR );
System.out.println( "Matching managed disks:" );
for( ManagedDiskDescriptor el : matching ) {
System.out.println( " " + el.getSession() );
}
ManagedDiskDigest digest = null;
UUID uuid = null;
if( !matching.isEmpty() ) {
ManagedDiskDescriptor recent = matching.get( matching.size()-1 );
log.info( "Retrieving uuid for: "+ recent );
uuid = store.uuid( recent );
if( debug )
System.out.println( "UUID: " + uuid );
log.info( "Requesting digest for: "+ recent );
digest = store.digest( recent );
if( digest == null ) {
log.warn( "No digest, continuing with full disk put" );
} else {
log.info( "Retrieved digest for " +
recent.getSession() + ": " +
digest.size() );
}
}
checkSession();
ManagedDiskDescriptor mdd = new ManagedDiskDescriptor( ud.getID(),
session );
System.out.println( "Storing: " + ud.getSource() +
" (" + ud.size() + " bytes) to " + mdd );
ManagedDisk md = null;
boolean useFlatDisk = ud.size() < 1024L * 1024 * 1024;
if( useFlatDisk ) {
md = new FlatDisk( ud, session );
} else {
if( uuid != null ){
md = new StreamOptimizedDisk( ud, session, uuid );
} else {
md = new StreamOptimizedDisk( ud, session );
}
md.setCompression( ManagedDisk.Compressions.SNAPPY );
}
if( digest != null ) {
md.setParentDigest( digest );
}
if( !isInteractive() ) {
store.put( md );
} else {
final long sz = ud.size();
ProgressMonitor.Callback cb = new ProgressMonitor.Callback() {
public void update( long in, long out, long elapsed ) {
double pc = in / (double)sz * 100;
System.out.print( (int)pc + "% " );
System.out.flush();
if( in == sz ) {
System.out.println();
System.out.printf( "Unmanaged size: %12d\n",
sz );
System.out.printf( "Managed size: %12d\n", out );
System.out.println( "Elapsed: " + elapsed );
}
}
};
int progressMonitorUpdateIntervalSecs = 5;
store.put( md, cb, progressMonitorUpdateIntervalSecs );
}
/*
Store various attributes about the UNMANAGED state that
serve as a context for the acquisition. None of these are
REQUIRED to be 'correct', they are purely informational.
*/
String user = System.getProperty( "user.name" );
store.setAttribute( mdd, "unmanaged.user",
user.getBytes() );
Date timestamp = new Date();
// storing the timestamp as a STRING
store.setAttribute( mdd, "unmanaged.timestamp",
("" + timestamp).getBytes() );
store.setAttribute( mdd, "unmanaged.path",
ud.getSource().getPath().getBytes() );
try {
InetAddress ia = InetAddress.getLocalHost();
String dotDecimal = ia.getHostAddress();
store.setAttribute( mdd, "unmanaged.inetaddress",
dotDecimal.getBytes() );
} catch( UnknownHostException uhe ) {
}
// If the disk's files have been hashed, add them too
if(diskFileRecords.containsKey(ud)){
System.out.println("Sending file records for disk");
// Add records for all partitions
List<Record> allRecords = new LinkedList<Record>();
for(BodyFile bodyFile : diskFileRecords.get(ud)){
allRecords.addAll(bodyFile.records());
}
// Send it
store.putFileRecords(mdd, allRecords);
System.out.println("File records sent");
} else {
// TODO - Check for a hash file and read/add it
System.out.println("No file records found in memory");
}
}
private void hashVolumeSystem( UnmanagedDisk ud ) throws IOException {
checkSession();
if( ud instanceof VirtualDisk ) {
hashVolumeSystemVirtual( (VirtualDisk)ud );
} else {
hashVolumeSystemNonVirtual( ud );
}
}
private void checkVMFS() throws IOException {
if( vmfs == null ) {
vmfs = new VirtualMachineFileSystem();
final VirtualMachineFileSystem vmfsF = vmfs;
Runtime.getRuntime().addShutdownHook( new Thread() {
public void run() {
try {
vmfsF.umount();
} catch( Exception e ) {
System.err.println( e );
}
}
} );
final File mountPoint = new File( "vmfs" );
mountPoint.mkdirs();
mountPoint.deleteOnExit();
try {
vmfs.mount( mountPoint, true );
} catch( Exception e ) {
throw new IOException( e );
}
}
}
private void hashVolumeSystemVirtual( VirtualDisk ud ) throws IOException {
checkVMFS();
VirtualMachine vm = ud.getVM();
vmfs.add( vm );
edu.uw.apl.vmvols.model.VirtualDisk vmDisk = ud.getDelegate();
File f = vmfs.pathTo( vmDisk );
Image i = new Image( f );
try {
hashVolumeSystemImpl( i, ud );
} finally {
// MUST release i else leaves vmfs non-unmountable
i.close();
}
}
private void hashVolumeSystemNonVirtual( UnmanagedDisk ud )
throws IOException {
Image i = new Image( ud.getSource() );
try {
hashVolumeSystemImpl( i, ud );
} finally {
i.close();
}
}
private void hashVolumeSystemImpl( Image i, UnmanagedDisk ud )
throws IOException {
VolumeSystem vs = null;
try {
vs = new VolumeSystem( i );
} catch( IllegalStateException noVolSys ) {
log.warn( noVolSys );
return;
}
try {
VolumeSystemHash vsh = VolumeSystemHash.create( vs );
StringWriter sw = new StringWriter();
VolumeSystemHashCodec.writeTo( vsh, sw );
String s = sw.toString();
ManagedDiskDescriptor mdd = new ManagedDiskDescriptor( ud.getID(),
session );
String key = "hashvs";
byte[] value = s.getBytes();
store.setAttribute( mdd, key, value );
} finally {
// MUST release vs else leaves vmfs non-unmountable
vs.close();
}
}
/**
* Write the file record data to a file
* @param fileHashes the map of file path to hash
* @param fileName the output file name
* @throws IOException
*/
private void writeRecordData(BodyFile bodyFile, String fileName) throws IOException{
List<Record> records = bodyFile.records();
// Replace / with _ so it doesnt try and write the file to some other directory
fileName = fileName.replace('/', '_');
System.out.println("Writing "+records.size()+" hashes to "+fileName);
// Get the writers ready
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(new BufferedWriter(fileWriter));
// Add the header
printWriter.println("MD5|name|inode|mode_as_string|UID|GID|size|atime|mtime|ctime|crtime");
// Print the records
for(Record record : records){
printWriter.println(record.toString());
}
// Flush and close the writers
printWriter.flush();
printWriter.close();
}
}
| 32.889847 | 182 | 0.599237 |
4ae73449a77d1b2d124a45dff3e8b07b92398d5f | 1,901 | package com.yiran.api.utils;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
public class CheckUtils {
public static final String COMMON_FIELD = "flowID,initiator,";
/**
* 验证对象是否为NULL,空字符串,空数组,空的Collection或Map(只有空格的字符串也认为是空串)
* @param obj 被验证的对象
* @param message 异常信息
*/
@SuppressWarnings("rawtypes")
public static void notEmpty(Object obj, String message) {
if (obj == null){
throw new IllegalArgumentException(message + " must be specified");
}
if (obj instanceof String && obj.toString().trim().length()==0){
throw new IllegalArgumentException(message + " must be specified");
}
if (obj.getClass().isArray() && Array.getLength(obj)==0){
throw new IllegalArgumentException(message + " must be specified");
}
if (obj instanceof Collection && ((Collection)obj).isEmpty()){
throw new IllegalArgumentException(message + " must be specified");
}
if (obj instanceof Map && ((Map)obj).isEmpty()){
throw new IllegalArgumentException(message + " must be specified");
}
}
/**
* 检查响应数据是否包含错误(key为customError、error_code)信息
* @param respData
* @return
*/
public static boolean hasError(Map<String, String> respData){
if (respData==null){
return true;
}
if (respData.get("customError")!=null){
return true;
}
if(!"0000".equals(respData.get("ret_code"))){
return true;
}
return false;
}
public static String getCustomError(Map<String, String> respData){
if (respData==null){
return null;
}
return respData.get("customError");
}
public static String getRetCode(Map<String, String> respData){
if (respData==null){
return null;
}
return respData.get("ret_code");
}
public static String getRetMsg(Map<String, String> respData){
if (respData==null){
return null;
}
if (respData.get("ret_msg")!=null){
return respData.get("ret_msg");
}
return null;
}
}
| 25.346667 | 70 | 0.687007 |
5f09eb8e1eaed3da83bbc062211163b89f6f311b | 284 | package de.fh_dortmund.inf.cw.phaseten.server.exceptions;
/**
* CardAlreadyTakenInThisTurnException
*
* @author Marc Mettke
*/
public class CardAlreadyTakenInThisTurnException extends MoveNotValidException {
private static final long serialVersionUID = 4739322323858292982L;
}
| 25.818182 | 80 | 0.816901 |
a0ce4cf2d0ee435486488a4a452c1d2047f2aa16 | 3,517 | package com.synopsys.integration.detectable.detectables.dart.functional;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Assertions;
import com.synopsys.integration.bdio.model.Forge;
import com.synopsys.integration.detectable.Detectable;
import com.synopsys.integration.detectable.DetectableEnvironment;
import com.synopsys.integration.detectable.ExecutableTarget;
import com.synopsys.integration.detectable.detectable.exception.DetectableException;
import com.synopsys.integration.detectable.detectable.executable.resolver.DartResolver;
import com.synopsys.integration.detectable.detectable.executable.resolver.FlutterResolver;
import com.synopsys.integration.detectable.detectable.util.EnumListFilter;
import com.synopsys.integration.detectable.detectables.dart.pubdep.DartPubDepsDetectableOptions;
import com.synopsys.integration.detectable.extraction.Extraction;
import com.synopsys.integration.detectable.functional.DetectableFunctionalTest;
import com.synopsys.integration.detectable.util.graph.NameVersionGraphAssert;
import com.synopsys.integration.executable.ExecutableOutput;
public class DartPubDepsDetectableTest extends DetectableFunctionalTest {
public DartPubDepsDetectableTest() throws IOException {
super("dart");
}
@Override
protected void setup() throws IOException {
addFile(Paths.get("pubspec.lock"));
addFile(Paths.get("pubspec.yaml"));
ExecutableOutput executableOutput = createStandardOutput(
"http_parser 3.1.5-dev",
"|-- pedantic 1.9.2",
"| '-- meta...",
"|-- source_span 1.7.0",
"| |-- meta 1.2.3",
"| |-- path 1.7.0"
);
addExecutableOutput(executableOutput, new File("dart").getAbsolutePath(), "pub", "deps");
}
@Override
@NotNull
public Detectable create(@NotNull DetectableEnvironment detectableEnvironment) {
class DartResolverTest implements DartResolver {
@Override
public ExecutableTarget resolveDart() throws DetectableException {
return ExecutableTarget.forFile(new File("dart"));
}
}
class FlutterResolverTest implements FlutterResolver {
@Override
public ExecutableTarget resolveFlutter() throws DetectableException {
return ExecutableTarget.forFile(new File("flutter"));
}
}
DartPubDepsDetectableOptions dartPubDepsDetectableOptions = new DartPubDepsDetectableOptions(EnumListFilter.excludeNone());
return detectableFactory.createDartPubDepDetectable(detectableEnvironment, dartPubDepsDetectableOptions, new DartResolverTest(), new FlutterResolverTest());
}
@Override
public void assertExtraction(@NotNull Extraction extraction) {
Assertions.assertNotEquals(0, extraction.getCodeLocations().size(), "A code location should have been generated.");
NameVersionGraphAssert graphAssert = new NameVersionGraphAssert(Forge.DART, extraction.getCodeLocations().get(0).getDependencyGraph());
graphAssert.hasRootSize(2);
graphAssert.hasRootDependency("pedantic", "1.9.2");
graphAssert.hasRootDependency("source_span", "1.7.0");
graphAssert.hasParentChildRelationship("source_span", "1.7.0", "meta", "1.2.3");
graphAssert.hasParentChildRelationship("source_span", "1.7.0", "path", "1.7.0");
}
}
| 44.518987 | 164 | 0.731589 |
9e5f720b498e4c085ba9281cde4d93f87f71e0fe | 19,769 | /**
* Project Name:OpenUniversity
* File Name:PersonSearchActicity.java
* Package Name:com.tming.openuniversity.activity
* Date:2014-6-9下午11:34:16
* Copyright (c) 2014, XueWenJian All Rights Reserved.
*
*/
package com.nd.shapedexamproj.activity.im;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.nd.shapedexamproj.App;
import com.nd.shapedexamproj.R;
import com.nd.shapedexamproj.activity.BaseActivity;
import com.nd.shapedexamproj.adapter.PersonSearchAdapter;
import com.nd.shapedexamproj.db.RelatedUserDBOperator;
import com.nd.shapedexamproj.entity.RelatedUserEntity;
import com.nd.shapedexamproj.im.model.PersonSearchResult;
import com.nd.shapedexamproj.im.model.RosterModel;
import com.nd.shapedexamproj.im.resource.IMConstants;
import com.nd.shapedexamproj.util.Constants;
import com.nd.shapedexamproj.util.JsonParseObject;
import com.nd.shapedexamproj.util.StringUtils;
import com.nd.shapedexamproj.util.UIHelper;
import com.tming.common.net.TmingHttp;
import com.tming.common.util.Log;
import com.tming.common.util.PhoneUtil;
import com.tming.common.view.support.pulltorefresh.PullToRefreshBase;
import com.tming.common.view.support.pulltorefresh.PullToRefreshListView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @项目名称: OpenUniversity
* @版本号 V1.1.0
* @所在包: com.tming.openuniversity.activity.im
* @文件名: PersonSearchActicity
* @文件描述: PersonSearchActicity 用户检索
* @创建人: XueWenJian
* @创建时间: 2014/6/9 11:08
* @修改记录:
* 1、Modified by xuwenzhuo On 2014/12/1
* 修改:根据交互需求修改功能
*
* @Copyright: 2014 Tming All rights reserved.
*/
public class PersonSearchActicity extends BaseActivity implements
OnClickListener {
private static final String TAG = "PersonSearchActicity";
/**
* 添加通讯录数据
* */
private static final int MSG_ADD_CONTACT_ITEM_DATA = 1;
private static final int IS_ADDED = 1;
private static final int NOT_ADDED = 0;
private Context mContext;
RelatedUserDBOperator relatedUserDBOperator;
private LinearLayout mLoadinglayout;
private RelativeLayout mHeadRL;
private ImageView mBackIV;
private TextView mHeadTitleTV;
private TextView mUserSearchWordsTV;
private Button mHeadRightBtn;
private EditText mSeachWordET;
private ImageView mCleanIV;
private Button mFindTV;
private PullToRefreshListView mResultLV;
private List<PersonSearchResult> mPersonSearchResults;
private PersonSearchAdapter mPersonSearchAdapter;
private int mPage = 1;
private int mPageSize = 10;
private List<RelatedUserEntity> mAddUserList;
private Drawable mGreenButtonBg;
private Drawable mWhiteButtonBg;
private int mOldTextColor;
private int mNewTextColor;
private TextView mSearchResultCountTextView;
private boolean mStateChanged;
private int mCurrentPosition;
@Override
public int initResource() {
return R.layout.im_personsearch_activity;
}
@Override
public void initComponent() {
mLoadinglayout = (LinearLayout) findViewById(R.id.loading_layout);
mHeadRL = (RelativeLayout) findViewById(R.id.common_head_layout);
mBackIV = (ImageView) findViewById(R.id.commonheader_left_iv);
mHeadTitleTV = (TextView) findViewById(R.id.commonheader_title_tv);
mHeadRightBtn = (Button) findViewById(R.id.commonheader_right_btn);
mSeachWordET = (EditText) findViewById(R.id.personsearch_search_et);
mSeachWordET.setCursorVisible(false);
mCleanIV = (ImageView) findViewById(R.id.personsearch_clean_iv);
mFindTV = (Button) findViewById(R.id.personsearch_find_tv);
mResultLV = (PullToRefreshListView) findViewById(R.id.personsearch_result_lv);
mUserSearchWordsTV=(TextView) findViewById(R.id.user_search_words_tv);
mSearchResultCountTextView=(TextView) findViewById(R.id.im_search_about_count_tv);
mHeadTitleTV.setText(R.string.im_personadd_title);
mHeadRightBtn.setVisibility(View.INVISIBLE);
mGreenButtonBg=getResources().getDrawable(R.drawable.null_foreground_button_pressed);
mWhiteButtonBg=getResources().getDrawable(R.drawable.green_white_button);
mOldTextColor= Color.WHITE;
mNewTextColor=getResources().getColor(R.color.head_btn_border);
}
@Override
public void initData() {
mContext = this;
mPersonSearchResults = new ArrayList<PersonSearchResult>();
mPersonSearchAdapter = new PersonSearchAdapter(mContext,
mPersonSearchResults);
mResultLV.setAdapter(mPersonSearchAdapter);
relatedUserDBOperator=new RelatedUserDBOperator(mContext);
//获取添加的用户列表
loadRelatedUserList();
mStateChanged=false;
}
@Override
public void addListener() {
mCleanIV.setOnClickListener(this);
mFindTV.setOnClickListener(this);
mSeachWordET.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//修改EditTextView的course状态
mSeachWordET.setCursorVisible(true);
}
});
mResultLV.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(
PullToRefreshBase<ListView> refreshView) {
Toast.makeText(mContext, "onPullDownToRefresh",
Toast.LENGTH_SHORT).show();
}
@Override
public void onPullUpToRefresh(
PullToRefreshBase<ListView> refreshView) {
nextPage();
}
});
mBackIV.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (mStateChanged){
//恢复状态
App.mRelatedUserStateFlag=Constants.USER_RELATEDSTAT_CHANGED;
//修改状态
mStateChanged=false;
}
PersonSearchActicity.this.finish();
}
});
mHeadTitleTV.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (mStateChanged){
//恢复状态
App.mRelatedUserStateFlag=Constants.USER_RELATEDSTAT_CHANGED;
//修改状态
mStateChanged=false;
}
PersonSearchActicity.this.finish();
}
});
mSeachWordET.addTextChangedListener(new TextWatcher() {
private CharSequence mTemp;
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// s:变化后的所有字符;start:字符起始的位置;before: 变化之前的总字节数;count:变化后的字节数
}
@Override
public void beforeTextChanged(CharSequence charSequence, int start,
int count, int after) {
// s:变化前的所有字符; start:字符开始的位置; count:变化前的总字节数;after:变化后的字节数
mTemp = charSequence;
}
@Override
public void afterTextChanged(Editable editable) {
// s:变化后的所有字符
if (mTemp.length() > 0) {
showClearBtn(true);
} else {
showClearBtn(false);
}
}
});
}
@Override
public void onClick(View view) {
if (R.id.personsearch_clean_iv == view.getId()) {
//清除按钮
String keyword = mSeachWordET.getText().toString();
if(!"".equals(keyword)){
mSeachWordET.setText("");
cleanReult();
showClearBtn(false);
mUserSearchWordsTV.setVisibility(View.VISIBLE);
}
} else if (R.id.personsearch_find_tv == view.getId()) {
if (PhoneUtil.checkNetworkEnable(mContext) == PhoneUtil.NETSTATE_DISABLE) {
Toast.makeText(mContext, getResources().getString(R.string.please_open_network), Toast.LENGTH_SHORT).show();
return;
}
String keyword = mSeachWordET.getText().toString();
if(!"".equals(keyword)){
cleanReult();
UIHelper.closeInputWindow(mContext, view);
findUsers(keyword);
} else {
UIHelper.ToastMessage(mContext, R.string.im_empty_error);
}
}
}
@Override
protected void onResume() {
super.onResume();
//好友状态已经发生改变
if (App.mRelatedUserStateFlag==Constants.USER_RELATEDSTAT_CHANGED){
mPersonSearchAdapter.changeSingleItemState(mCurrentPosition);
//恢复状态
App.mRelatedUserStateFlag=Constants.USER_RELATEDSTAT_NOTCHANGE;
//修改状态
mStateChanged=true;
saveRelatedUserToDB(mPersonSearchAdapter.getData().get(mCurrentPosition));
}
}
private void cleanReult() {
mPage = 1;
mPersonSearchResults.clear();
mPersonSearchAdapter.notifyDataSetChanged();
}
private void nextPage() {
String keyword = mSeachWordET.getText().toString();
findUsers(keyword);
}
/**
* 根据关键字查找用户
* @param keyWord
*/
private void findUsers(String keyWord) {
if (StringUtils.isEmpty(keyWord)) {
mResultLV.onRefreshComplete();
UIHelper.ToastMessage(mContext, R.string.im_empty_error);
return;
}
mLoadinglayout.setVisibility(View.VISIBLE);
String url = Constants.SEARCH_USER;
Map<String, Object> params = new HashMap<String, Object>();
params.put("keyword", keyWord);
params.put("pageNum", mPage);
params.put("pageSize", mPageSize);
TmingHttp.asyncRequest(url, params, new TmingHttp.RequestCallback<List<PersonSearchResult>>() {
@Override
public List<PersonSearchResult> onReqestSuccess(String respones) throws Exception {
// 数据组装
JsonParseObject jsonParseObject = JsonParseObject
.parseJson(respones);
List<PersonSearchResult> result = null;
if (Constants.SUCCESS_MSG == jsonParseObject.getFlag()) {
try {
if (Constants.SUCCESS_MSG == jsonParseObject.getResJs().getInt("code")) {
if (!jsonParseObject.getResJs().getJSONObject("data").isNull("list")) {
Gson gson = new GsonBuilder().setDateFormat(
"yyyy-MM-dd").create();
result = gson.fromJson(jsonParseObject.getResJs().getJSONObject("data")
.getJSONArray("list")
.toString(),
new TypeToken<ArrayList<PersonSearchResult>>() {
}.getType());
if (result.size() > 0) {
mPage++;
}
//重新设定添加关系,跟本地数据库进行对比,如果本地数据库中存在,则改变用户状态:已经添加
//如果没有,保持原来状态
result = resetUserRelatedFlag(result);
}
}
} catch (JsonSyntaxException e) {
e.printStackTrace();
jsonParseObject.setFlag(0);
}
}
return result;
}
@Override
public void success(List<PersonSearchResult> result) {
mResultLV.onRefreshComplete();
// UI表现
if (result != null) {
mPersonSearchResults.addAll(result);
mPersonSearchAdapter.notifyDataSetChanged();
if (mPersonSearchResults.size() == 0) {
UIHelper.ToastMessage(mContext,
R.string.im_result_empty_text);
mUserSearchWordsTV.setVisibility(View.VISIBLE);
} else {
mUserSearchWordsTV.setVisibility(View.GONE);
}
mSearchResultCountTextView.setText("( " + mPersonSearchResults.size() + " )人");
} else {
Toast.makeText(mContext, R.string.api_error,
Toast.LENGTH_SHORT).show();
mSearchResultCountTextView.setText("( 0 )人");
return;
}
mLoadinglayout.setVisibility(View.GONE);
}
@Override
public void exception(Exception exception) {
exception.printStackTrace();
}
});
}
/**
* 显示隐藏清除按钮
* @param able
*/
private void showClearBtn(boolean able) {
if (able) {
mCleanIV.setVisibility(View.VISIBLE);
} else {
mCleanIV.setVisibility(View.GONE);
}
}
private Button personsearchAddBtn;
private class AddContactPersonAsyncTask extends
AsyncTask<PersonSearchResult, Void, Integer> {
@Override
protected Integer doInBackground(PersonSearchResult... arg0) {
PersonSearchResult personSearchResult = arg0[0];
RosterModel model = new RosterModel();
Integer reult = RosterModel.RESULT_SUCCESS;
if(App.getUserId().equals(personSearchResult.getUserId())){
//提示不能添加自己为好友
reult = RosterModel.RESULT_ERROR_SELF;
} else {
reult = model.addRoster(mContext, personSearchResult.getUserId()
+ "@" + IMConstants.areaServerName,
personSearchResult.getUserName());
}
return reult;
}
@Override
protected void onPostExecute(Integer result) {
if (RosterModel.RESULT_SUCCESS == result) {
UIHelper.ToastMessage(mContext, R.string.im_add_result_success);
} else if(RosterModel.RESULT_ERROR_ADD == result){
UIHelper.ToastMessage(mContext, R.string.im_add_result_error_add);
} else if(RosterModel.RESULT_ERROR_EXIST == result){
UIHelper.ToastMessage(mContext, R.string.im_add_result_error_exist);
} else if(RosterModel.RESULT_ERROR_SELF == result){
UIHelper.ToastMessage(mContext, R.string.im_add_result_error_self);
} else {
UIHelper.ToastMessage(mContext, R.string.im_add_result_error_undefined);
}
mLoadinglayout.setVisibility(View.GONE);
super.onPostExecute(result);
}
}
/**
* 发送关注请求 ,在 im_personsearch_item
* @param view cell控件
*
*/
public void addRelatedRequest(View view){
try{
int posision=(Integer)view.getTag();
PersonSearchResult personSearchResult=mPersonSearchAdapter.getmPersonSearchResults().get(posision);
if (personSearchResult!=null){
String userId =personSearchResult.getUserId();
//用户添加自己操作
if (App.getUserId().equals(userId)){
Toast.makeText(PersonSearchActicity.this, R.string.im_add_result_error_self, Toast.LENGTH_SHORT).show();
return;
}
Map<String ,Object> params = new HashMap<String,Object>();
params.put("userid", App.getUserId());
params.put("followid", userId);
params.put("type", Constants.PERSON_RELATION_FOLLOW);
String url = Constants.ADD_FRIENDS_URL ;
changeFriendState(url,params,(Button)view);
mPersonSearchAdapter.changeSingleItemState(posision,1);
saveRelatedUserToDB(personSearchResult);
//设定标示
App.mRelatedUserStateFlag=Constants.USER_RELATEDSTAT_CHANGED;
}
} catch(Exception exception){
Toast.makeText(PersonSearchActicity.this, R.string.api_error, Toast.LENGTH_SHORT).show();
//设定标示
App.mRelatedUserStateFlag=Constants.USER_RELATEDSTAT_NOTCHANGE;
}
}
/**
* 加关注或取消关注
* @param url
* @param params
*/
private void changeFriendState(String url,Map<String ,Object> params,final Button view){
Log.d(TAG, url);
TmingHttp.asyncRequest(url, params, new TmingHttp.RequestCallback<Integer>() {
@Override
public Integer onReqestSuccess(String respones) throws Exception {
return addJsonParsing(respones);
}
@Override
public void success(Integer respones) {
//提示消失
mLoadinglayout.setVisibility(View.GONE);
if (respones != Constants.SUCCESS_MSG) {
//添加关注失败
Toast.makeText(PersonSearchActicity.this, R.string.api_error, Toast.LENGTH_SHORT).show();
return;
} else {
//添加关注成功
Toast.makeText(PersonSearchActicity.this, R.string.follow_add, Toast.LENGTH_SHORT).show();
changeButtonState(view, 1);
}
}
@Override
public void exception(Exception exception) {
mLoadinglayout.setVisibility(View.GONE);
Toast.makeText(PersonSearchActicity.this, getResources().getString(R.string.net_error), Toast.LENGTH_SHORT).show();
exception.printStackTrace();
}
});
}
/**
* 跳转到用户信息页面
* @param view 用户圆形头像view
*/
public void jumpToSearchUserDetail(View view){
int posision=(Integer)view.getTag();
if(mPersonSearchAdapter.getData()==null||mPersonSearchAdapter.getData().size()<=posision){
return;
} else {
PersonSearchResult personSearchResult = mPersonSearchAdapter.getData().get(posision);
//由于关注关系的原因,导致userid字段的不确定,程序中首先判定一次
String userId = personSearchResult.getUserId();
//不是点击用户自身
if (!App.getUserId().equals(userId)){
//跳转到好友信息界面
UIHelper.showFriendInfoActivity(PersonSearchActicity.this,userId);
mCurrentPosition=posision;
} else{
//选择用户自身
}
}
}
/**
* 修改数据库中关系状态,根据现在设定,在数据库中增加一条记录
* @param personSearchResult 需要保存的对象
*/
private void saveRelatedUserToDB(PersonSearchResult personSearchResult){
if (personSearchResult.getIsAdded()==1){
relatedUserDBOperator.insertRelationShipWithSearchPersonObject(personSearchResult);
} else{
relatedUserDBOperator.deleteRelationShipWithSearchPersonObject(personSearchResult);
}
loadRelatedUserList();
}
/**
* 修改按钮状态
* @param view 按钮视图
* @param state 状态参数 0 :没有添加
* 1 :已经添加
*/
private void changeButtonState(final Button view,int state){
if (state==1) {
//修改为已经添加
view.setText(R.string.msg_have_added);
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.JELLY_BEAN){
view.setTextColor(mNewTextColor);
view.setBackground(mWhiteButtonBg);
}
} else {
//修改为没有添加
view.setText(R.string.add);
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.JELLY_BEAN){
view.setTextColor(mOldTextColor);
view.setBackground(mGreenButtonBg);
}
}
}
/**
* 获取已经添加的用户列表
*/
private void loadRelatedUserList(){
mAddUserList=relatedUserDBOperator.queryRelatedUsersWithId(App.getUserId());
}
/**
* 根据查询的数据结果,在本地数据库中查询,并修改状态,是否为添加或者已添加
* @param userList
*/
private List<PersonSearchResult> resetUserRelatedFlag(List<PersonSearchResult> userList){
List<PersonSearchResult> results=userList;
boolean isself=false;
for (int i=0;i<results.size();i++){
PersonSearchResult result=userList.get(i);
//判定是否为本人,如果为本人,则过滤
/*
if (!isself && result.getUserId().equals(App.getUserId())){
isself=true;
results.remove(result);
i-=1;
continue;
}
*/
//设定搜索结果状态“添加/已添加"
result.setIsAdded(0);
for (int j=0;j<mAddUserList.size();j++){
if (mAddUserList.get(j).getmRelatedId().equals(result.getUserId())){
result.setIsAdded(1);
}
}
}
return results;
}
/**
* 添加好友结果字符串解析
* @param result 返回的json字符串
* @return int 型结果
*/
private int addJsonParsing(String result){
Log.d(TAG, result);
int flag = 0;
try {
JSONObject jobj = new JSONObject(result);
flag = jobj.getInt("flag");
if(flag != 1 && !jobj.isNull("msg")){
String msg = jobj.getString("msg");
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return flag;
}
@Override
public void onBackPressed() {
//修改状态
if (mStateChanged){
App.mRelatedUserStateFlag= Constants.USER_RELATEDSTAT_CHANGED;
}
finish();
super.onBackPressed();
}
}
| 31.479299 | 124 | 0.665942 |
09838b974057fbcd5feeff16e6494d7441f5c833 | 6,764 | package com.github.project.videoeditor.gui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import javax.swing.*;
import com.github.project.videoeditor.container.Marker;
import com.github.project.videoeditor.container.Movie;
import com.github.project.videoeditor.model.MarkerHandler;
/**
*
* @author Peter Gessler
* @version 1.0
* @DevelopmentDate 03.01.2016
* @LastUpdate -
* @Assignment Frame to edit a marker.
*
*/
public class MarkerEditorFrame {
JFrame markerEditframeParent = null;
private int markerId;
private String markerName;
private double startTime;
private double endTime;
private JLabel idLabel;
private JLabel nameLabel;
private JLabel startTimeLabel;
private JLabel endTimeLabel;
private JLabel idTxtLabel;
private JTextField nameTxtField;
private JTextField startTimeTxtFieldMin;
private JTextField startTimeTxtFieldSec;
private JTextField startTimeTxtFieldMilliSeconds;
private JTextField endTimeTxtFieldMin;
private JTextField endTimeTxtFieldSec;
private JTextField endTimeTxtFieldMilliSeconds;
private JButton saveButton;
private JButton abortButton;
private String[] labels = { "Id: ", "Name: ", "Start in Min/Sec/Ms: ",
"End in Min/Sec/Ms: " };
private static volatile MarkerEditorFrame singleton = null;
public static synchronized MarkerEditorFrame getInstance() {
if (singleton == null)
singleton = new MarkerEditorFrame();
return singleton;
}
// Constructor
private MarkerEditorFrame() {
// Create and set up the window.
markerEditframeParent = new JFrame("Marker Editor");
markerEditframeParent.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panelContent = new JPanel(new GridLayout(0, 2));
// id components
idLabel = new JLabel(labels[0]);
idTxtLabel = new JLabel("-");
idTxtLabel.setLabelFor(idLabel);
panelContent.add(idLabel);
panelContent.add(idTxtLabel);
// name components
nameLabel = new JLabel(labels[1]);
nameTxtField = new JTextField(10);
nameLabel.setLabelFor(nameTxtField);
panelContent.add(nameLabel);
panelContent.add(nameTxtField);
// startTime components
startTimeLabel = new JLabel(labels[2]);
JPanel startTimePanel = new JPanel(new GridLayout(0, 3));
startTimeTxtFieldMin = new JTextField(2);
startTimeTxtFieldSec = new JTextField(2);
startTimeTxtFieldMilliSeconds = new JTextField(2);
startTimeLabel.setLabelFor(startTimePanel);
startTimePanel.add(startTimeTxtFieldMin);
startTimePanel.add(startTimeTxtFieldSec);
startTimePanel.add(startTimeTxtFieldMilliSeconds);
panelContent.add(startTimeLabel);
panelContent.add(startTimePanel);
// endTime components
endTimeLabel = new JLabel(labels[3]);
JPanel endTimePanel = new JPanel(new GridLayout(0, 3));
endTimeTxtFieldMin = new JTextField(2);
endTimeTxtFieldSec = new JTextField(2);
endTimeTxtFieldMilliSeconds = new JTextField(2);
endTimeLabel.setLabelFor(endTimePanel);
endTimePanel.add(endTimeTxtFieldMin);
endTimePanel.add(endTimeTxtFieldSec);
endTimePanel.add(endTimeTxtFieldMilliSeconds);
panelContent.add(endTimeLabel);
panelContent.add(endTimePanel);
// button components
saveButton = new JButton(new AbstractAction() {
private static final long serialVersionUID = 3953683242917043246L;
@Override
public void actionPerformed(ActionEvent e) {
saveValues();
}
});
saveButton.setName("Speichern");
saveButton.setText("Speichern");
abortButton = new JButton(new AbstractAction() {
/**
*
*/
private static final long serialVersionUID = 6278932109092556121L;
@Override
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
abortButton.setName("Abbrechen");
abortButton.setText("Abbrechen");
panelContent.add(saveButton);
panelContent.add(abortButton);
// Set up the content pane.
panelContent.setOpaque(true); // content panes must be opaque
markerEditframeParent.setContentPane(panelContent);
}
public void showMarkereditorFrame() {
// Display the window.
markerEditframeParent.pack();
markerEditframeParent.setVisible(true);
}
// method to init marker values
public void initMarkerValues(Marker marker) {
markerId = marker.getMarkerId();
idTxtLabel.setText(String.valueOf(marker.getMarkerId()));
nameTxtField.setText(marker.getMarkerName());
startTimeTxtFieldMin.setText(String.valueOf(formatTime(
marker.getStartTime()).getMinutes()));
startTimeTxtFieldSec.setText(String.valueOf(formatTime(
marker.getStartTime()).getSeconds()));
startTimeTxtFieldMilliSeconds.setText(String.valueOf(formatTime(
marker.getStartTime()).getMilliSeconds()));
endTimeTxtFieldMin.setText(String.valueOf(formatTime(
marker.getEndTime()).getMinutes()));
endTimeTxtFieldSec.setText(String.valueOf(formatTime(
marker.getEndTime()).getSeconds()));
endTimeTxtFieldMilliSeconds.setText(String.valueOf(formatTime(
marker.getEndTime()).getMilliSeconds()));
}
// store new values
private void saveValues() {
markerName = nameTxtField.getText();
startTime = deformatTime(startTimeTxtFieldMin.getText(),
startTimeTxtFieldSec.getText(),
startTimeTxtFieldMilliSeconds.getText());
endTime = deformatTime(endTimeTxtFieldMin.getText(),
endTimeTxtFieldSec.getText(),
endTimeTxtFieldMilliSeconds.getText());
if (startTime < endTime && endTime < Movie.getInstance().getMovDuration()) {
MarkerHandler.getInstance().editMarker(markerId,
new Marker(markerId, markerName, startTime, endTime));
closeWindow();
}
}
// close frame without storing
private void closeWindow() {
markerEditframeParent.dispatchEvent(new WindowEvent(
markerEditframeParent, WindowEvent.WINDOW_CLOSING));
}
// format to String
private TimeView formatTime(double time) {
int minutes = (int) (time / 60);
int seconds = (int) (time % 60);
long iPart = (long) time;
int milliSeconds = (int) ((time - iPart) * 100);
return (new TimeView(minutes, seconds, milliSeconds));
}
// format to double
private double deformatTime(String minutes, String seconds,
String milliSeconds) {
int inSeconds = (Integer.valueOf(minutes) * 60)
+ Integer.valueOf(seconds);
double milliSec = Double.valueOf(milliSeconds) / 100;
double deformatedTime = inSeconds + milliSec;
return deformatedTime;
}
public static void main(String[] args) {
MarkerEditorFrame.getInstance();
MarkerEditorFrame.getInstance().initMarkerValues(
new Marker(0, "Frost", 48.500, 122.260));
}
}
| 28.540084 | 79 | 0.72531 |
a2545ab31bcd16c503a6de958da24be9da51eb1a | 13,185 | /*******************************************************************************
* Copyright SemanticBits, Northwestern University and Akaza Research
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caaers/LICENSE.txt for details.
******************************************************************************/
package gov.nih.nci.cabig.caaers.web.ae;
import gov.nih.nci.cabig.caaers.dao.OrganizationDao;
import gov.nih.nci.cabig.caaers.dao.ParticipantDao;
import gov.nih.nci.cabig.caaers.dao.PersonDao;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.dao.StudySiteDao;
import gov.nih.nci.cabig.caaers.domain.Investigator;
import gov.nih.nci.cabig.caaers.domain.Person;
import gov.nih.nci.cabig.caaers.domain.ReportStatus;
import gov.nih.nci.cabig.caaers.domain.ReviewStatus;
import gov.nih.nci.cabig.caaers.domain.dto.AdverseEventReportingPeriodDTO;
import gov.nih.nci.cabig.caaers.domain.dto.RoutingAndReviewSearchResultsDTO;
import gov.nih.nci.cabig.caaers.domain.repository.AdverseEventRoutingAndReviewRepository;
import gov.nih.nci.cabig.caaers.security.SecurityUtils;
import gov.nih.nci.cabig.caaers.service.workflow.WorkflowService;
import gov.nih.nci.cabig.caaers.tools.configuration.Configuration;
import gov.nih.nci.cabig.caaers.tools.editors.EnumByNameEditor;
import gov.nih.nci.cabig.caaers.web.ControllerTools;
import java.util.*;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
/**
* @author Sameer Sawant
* @author Biju Joseph
*/
public class RoutingAndReviewController extends SimpleFormController{
protected MessageSource messageSource;
private ParticipantDao participantDao;
private StudyDao studyDao;
private StudySiteDao studySiteDao;
private OrganizationDao organizationDao;
private Configuration configuration;
private AdverseEventRoutingAndReviewRepository adverseEventRoutingAndReviewRepository;
private WorkflowService workflowService;
protected static final Collection<ReviewStatus> REVIEW_STATUS = new ArrayList<ReviewStatus>(7);
private static final String PAGINATION_ACTION = "paginationAction";
private static final String CURRENT_PAGE_NUMBER = "currentPageNumber";
PersonDao personDao;
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
static{
REVIEW_STATUS.addAll(Arrays.asList(ReviewStatus.values()));
}
public RoutingAndReviewController() {
setCommandClass(RoutingAndReviewCommand.class);
setBindOnNewForm(true);
setFormView("ae/selectRoutingAndReview");
setSuccessView("ae/routingAndReviewResult");
}
@Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
RoutingAndReviewCommand command = new RoutingAndReviewCommand();
command.setWorkflowEnabled(configuration.get(Configuration.ENABLE_WORKFLOW));
command.setReviewStatusList(workflowService.allowedReviewStatuses(SecurityUtils.getUserLoginName()));
if(!command.getWorkflowEnabled()){
request.setAttribute("warning.routingAndReview.notenabled", messageSource.getMessage("warning.routingAndReview.notenabled", new Object[]{}, "Course routing and review is not enabled, so the search may not return any result", Locale.getDefault()));
}
return command;
}
@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
ControllerTools.registerGridDomainObjectEditor(binder, "participant", participantDao);
ControllerTools.registerGridDomainObjectEditor(binder, "study", studyDao);
ControllerTools.registerGridDomainObjectEditor(binder, "organization", organizationDao);
//ControllerTools.registerDomainObjectEditor(binder, studySiteDao);
binder.registerCustomEditor(ReviewStatus.class, new EnumByNameEditor(ReviewStatus.class));
binder.registerCustomEditor(ReportStatus.class, new EnumByNameEditor(ReportStatus.class));
}
/**
* It is a form submission, if participant, or study is available
*/
@Override
@SuppressWarnings("unchecked")
protected boolean isFormSubmission(HttpServletRequest request) {
Set<String> paramNames = request.getParameterMap().keySet();
boolean hasParticipant = paramNames.contains("participant");
boolean hasStudy = paramNames.contains("study");
boolean hasSite = paramNames.contains("organization");
boolean hasReportStatus = paramNames.contains("reportStatus");
boolean hasReviewStatus = paramNames.contains("reviewStatus");
String paginationAction = (String)findInRequest(request, PAGINATION_ACTION);
return hasParticipant || hasStudy || hasSite || hasReportStatus || hasReviewStatus || paginationAction != null;
}
@Override
protected ModelAndView processFormSubmission(HttpServletRequest request,HttpServletResponse response, Object command, BindException errors) throws Exception {
RoutingAndReviewCommand cmd = (RoutingAndReviewCommand)command;
String userId = SecurityUtils.getUserLoginName();
Boolean isStaff = true;
Person loggedInPerson = personDao.getByLoginId(userId);
if(loggedInPerson instanceof Investigator){
isStaff = false;
}
request.setAttribute("isStaff", isStaff);
ModelAndView modelAndView = super.processFormSubmission(request, response, command, errors);
if(!errors.hasErrors()){
List<AdverseEventReportingPeriodDTO> rpDtos = adverseEventRoutingAndReviewRepository.findAdverseEventReportingPeriods(cmd.getParticipant(), cmd.getStudy(), cmd.getOrganization(), cmd.getReviewStatus(), cmd.getReportStatus(), userId, configuration.get(Configuration.ENABLE_WORKFLOW));
RoutingAndReviewSearchResultsDTO searchResultsDTO = new RoutingAndReviewSearchResultsDTO(cmd.isSearchCriteriaStudyCentric(), cmd.isSearchCriteriaParticipantCentric(), cmd.getParticipant(), cmd.getStudy(), rpDtos);
cmd.setSearchResultsDTO(searchResultsDTO);
processPaginationSubmission(request, cmd, modelAndView);
String numberOfResultsPerPage = (String) findInRequest(request, "numberOfResultsPerPage");
if(numberOfResultsPerPage == null)
modelAndView.getModel().put("numberOfResultsPerPage", 5);
else
modelAndView.getModel().put("numberOfResultsPerPage", Integer.parseInt(numberOfResultsPerPage));
Integer currentPageNumber = (Integer) request.getSession().getAttribute(CURRENT_PAGE_NUMBER);
if(currentPageNumber.equals(1))
modelAndView.getModel().put("isFirstPage", true);
else
modelAndView.getModel().put("isFirstPage", false);
if(isLastPage(request, cmd))
modelAndView.getModel().put("isLastPage", true);
else
modelAndView.getModel().put("isLastPage", false);
// Determine if the user is brought to this page because the course was deleted (retired)
String courseRetired = (String) findInRequest(request, "retiredReportingPeriod");
if(courseRetired != null && courseRetired.equals("true"))
modelAndView.getModel().put("courseRetired", "true");
}
return modelAndView;
}
protected void processPaginationSubmission(HttpServletRequest request, RoutingAndReviewCommand command, ModelAndView modelAndView){
String action = (String) findInRequest(request, PAGINATION_ACTION);
String numberOfResultsPerPage = (String) findInRequest(request, "numberOfResultsPerPage");
Integer currPageNumber = (Integer)request.getSession().getAttribute(CURRENT_PAGE_NUMBER);
if(currPageNumber == null)
currPageNumber = 1;
Integer newPageNumber = 0;
if(action.equals("nextPage")){
newPageNumber = ++currPageNumber;
}else if(action.equals("prevPage")){
newPageNumber = --currPageNumber;
}else if(action.equals("lastPage")){
Float newPageNumberFloat = command.getSearchResultsDTO().getTotalResultCount() / Float.parseFloat(numberOfResultsPerPage);
newPageNumber = newPageNumberFloat.intValue();
if(command.getSearchResultsDTO().getTotalResultCount() % Integer.parseInt(numberOfResultsPerPage) > 0)
newPageNumber++;
}else if(action.equals("firstPage") || action.equals("numberOfResultsPerPage")){
newPageNumber = 1;
}
Integer startIndex = (newPageNumber - 1) * Integer.parseInt(numberOfResultsPerPage);
Integer endIndex = newPageNumber * Integer.parseInt(numberOfResultsPerPage) - 1;
if(endIndex > command.getSearchResultsDTO().getTotalResultCount())
endIndex = command.getSearchResultsDTO().getTotalResultCount() - 1;
command.getSearchResultsDTO().filterResultMap(startIndex, endIndex);
request.getSession().setAttribute(CURRENT_PAGE_NUMBER, newPageNumber);
modelAndView.getModel().put("totalResults", command.getSearchResultsDTO().getTotalResultCount());
modelAndView.getModel().put("startIndex", startIndex + 1);
modelAndView.getModel().put("endIndex", endIndex + 1);
}
protected boolean isLastPage(HttpServletRequest request, RoutingAndReviewCommand command){
String action = (String) findInRequest(request, PAGINATION_ACTION);
if(action != null && action.equals("lastPage"))
return true;
String numberOfResultsPerPage = (String) findInRequest(request, "numberOfResultsPerPage");
Integer currentPageNumber = (Integer)request.getSession().getAttribute(CURRENT_PAGE_NUMBER);
if(currentPageNumber * Integer.parseInt(numberOfResultsPerPage) > command.getSearchResultsDTO().getTotalResultCount())
return true;
return false;
}
@Override
protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception {
RoutingAndReviewCommand cmd = (RoutingAndReviewCommand)command;
if(!cmd.criteriaHasParticipant() && !cmd.criteriaHasStudy() && !cmd.criteriaHasSite() && !cmd.criteriaHasReviewStatus() && !cmd.criteriaHasReportStatus()){
errors.reject("RAR_004", "Missing search criterion");
}
}
/**
* Returns the value associated with the <code>attributeName</code>, if present in
* HttpRequest parameter, if not available, will check in HttpRequest attribute map.
*/
protected Object findInRequest(final ServletRequest request, final String attributName) {
Object attr = request.getParameter(attributName);
if (attr == null) {
attr = request.getAttribute(attributName);
}
return attr;
}
@Override
@SuppressWarnings("unchecked")
protected Map referenceData(HttpServletRequest request, Object cmd, Errors errors)
throws Exception {
return null;
}
public void setParticipantDao(ParticipantDao participantDao) {
this.participantDao = participantDao;
}
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
public void setStudySiteDao(StudySiteDao studySiteDao){
this.studySiteDao = studySiteDao;
}
public AdverseEventRoutingAndReviewRepository getAdverseEventRoutingAndReviewRepository() {
return adverseEventRoutingAndReviewRepository;
}
public void setAdverseEventRoutingAndReviewRepository(
AdverseEventRoutingAndReviewRepository adverseEventRoutingAndReviewRepository) {
this.adverseEventRoutingAndReviewRepository = adverseEventRoutingAndReviewRepository;
}
public WorkflowService getWorkflowService(){
return workflowService;
}
public void setWorkflowService(WorkflowService workflowService){
this.workflowService = workflowService;
}
public void setConfiguration(Configuration configuration){
this.configuration = configuration;
}
public Configuration getConfiguration(){
return configuration;
}
public void setOrganizationDao(OrganizationDao organizationDao) {
this.organizationDao = organizationDao;
}
public MessageSource getMessageSource() {
return messageSource;
}
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
}
| 44.846939 | 290 | 0.719909 |
f9584d937e4b3a02f9de991e3cffc4528ea1de55 | 178,073 | /*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.nomina.presentation.swing.jinternalframes.report;
import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*;
import com.bydan.erp.nomina.presentation.web.jsf.sessionbean.*;//.report;
import com.bydan.erp.nomina.presentation.swing.jinternalframes.*;
import com.bydan.erp.nomina.presentation.swing.jinternalframes.auxiliar.report.*;
import com.bydan.erp.nomina.presentation.web.jsf.sessionbean.report.*;
import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.seguridad.business.entity.*;
//import com.bydan.erp.nomina.presentation.report.source.report.*;
import com.bydan.framework.erp.business.entity.Reporte;
import com.bydan.erp.seguridad.business.entity.Modulo;
import com.bydan.erp.seguridad.business.entity.Opcion;
import com.bydan.erp.seguridad.business.entity.Usuario;
import com.bydan.erp.seguridad.business.entity.ResumenUsuario;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralSg;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralUsuario;
import com.bydan.erp.seguridad.util.SistemaParameterReturnGeneral;
import com.bydan.erp.nomina.business.entity.report.*;
import com.bydan.erp.nomina.util.report.ProcesoUtilidadesConstantesFunciones;
import com.bydan.erp.nomina.business.logic.report.*;
import com.bydan.framework.erp.business.entity.DatoGeneral;
import com.bydan.framework.erp.business.entity.OrderBy;
import com.bydan.framework.erp.business.entity.Mensajes;
import com.bydan.framework.erp.business.entity.Classe;
import com.bydan.framework.erp.business.logic.*;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverter;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverterFromDate;
import com.bydan.framework.erp.presentation.desktop.swing.FuncionesSwing;
import com.bydan.framework.erp.presentation.desktop.swing.JInternalFrameBase;
import com.bydan.framework.erp.presentation.desktop.swing.*;
import com.bydan.framework.erp.util.*;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.*;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.TableColumn;
import com.toedter.calendar.JDateChooser;
@SuppressWarnings("unused")
public class ProcesoUtilidadesJInternalFrame extends ProcesoUtilidadesBeanSwingJInternalFrameAdditional {
private static final long serialVersionUID = 1L;
//protected Usuario usuarioActual=null;
public JToolBar jTtoolBarProcesoUtilidades;
protected JMenuBar jmenuBarProcesoUtilidades;
protected JMenu jmenuProcesoUtilidades;
protected JMenu jmenuDatosProcesoUtilidades;
protected JMenu jmenuArchivoProcesoUtilidades;
protected JMenu jmenuAccionesProcesoUtilidades;
protected JPanel jContentPane = null;
protected JPanel jPanelBusquedasParametrosProcesoUtilidades = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
protected GridBagLayout gridaBagLayoutProcesoUtilidades;
protected GridBagConstraints gridBagConstraintsProcesoUtilidades;
//protected JInternalFrameBase jInternalFrameParent;
public ProcesoUtilidadesDetalleFormJInternalFrame jInternalFrameDetalleFormProcesoUtilidades;
protected ReporteDinamicoJInternalFrame jInternalFrameReporteDinamicoProcesoUtilidades;
protected ImportacionJInternalFrame jInternalFrameImportacionProcesoUtilidades;
//VENTANAS PARA ACTUALIZAR Y BUSCAR FK
protected AnioBeanSwingJInternalFrame anioBeanSwingJInternalFrame;
public String sFinalQueryGeneral_anio="";
public ProcesoUtilidadesSessionBean procesoutilidadesSessionBean;
public AnioSessionBean anioSessionBean;
//protected JDesktopPane jDesktopPane;
public List<ProcesoUtilidades> procesoutilidadess;
public List<ProcesoUtilidades> procesoutilidadessEliminados;
public List<ProcesoUtilidades> procesoutilidadessAux;
protected OrderByJInternalFrame jInternalFrameOrderByProcesoUtilidades;
protected JButton jButtonAbrirOrderByProcesoUtilidades;
//protected JPanel jPanelOrderByProcesoUtilidades;
//public JScrollPane jScrollPanelOrderByProcesoUtilidades;
//protected JButton jButtonCerrarOrderByProcesoUtilidades;
public ArrayList<OrderBy> arrOrderBy= new ArrayList<OrderBy>();
public ProcesoUtilidadesLogic procesoutilidadesLogic;
public JScrollPane jScrollPanelDatosProcesoUtilidades;
public JScrollPane jScrollPanelDatosEdicionProcesoUtilidades;
public JScrollPane jScrollPanelDatosGeneralProcesoUtilidades;
//public JScrollPane jScrollPanelDatosProcesoUtilidadesOrderBy;
//public JScrollPane jScrollPanelReporteDinamicoProcesoUtilidades;
//public JScrollPane jScrollPanelImportacionProcesoUtilidades;
protected JPanel jPanelAccionesProcesoUtilidades;
protected JPanel jPanelPaginacionProcesoUtilidades;
protected JPanel jPanelParametrosReportesProcesoUtilidades;
protected JPanel jPanelParametrosReportesAccionesProcesoUtilidades;
;
protected JPanel jPanelParametrosAuxiliar1ProcesoUtilidades;
protected JPanel jPanelParametrosAuxiliar2ProcesoUtilidades;
protected JPanel jPanelParametrosAuxiliar3ProcesoUtilidades;
protected JPanel jPanelParametrosAuxiliar4ProcesoUtilidades;
//protected JPanel jPanelParametrosAuxiliar5ProcesoUtilidades;
//protected JPanel jPanelReporteDinamicoProcesoUtilidades;
//protected JPanel jPanelImportacionProcesoUtilidades;
public JTable jTableDatosProcesoUtilidades;
//public JTable jTableDatosProcesoUtilidadesOrderBy;
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
protected JButton jButtonNuevoProcesoUtilidades;
protected JButton jButtonDuplicarProcesoUtilidades;
protected JButton jButtonCopiarProcesoUtilidades;
protected JButton jButtonVerFormProcesoUtilidades;
protected JButton jButtonNuevoRelacionesProcesoUtilidades;
protected JButton jButtonModificarProcesoUtilidades;
protected JButton jButtonGuardarCambiosTablaProcesoUtilidades;
protected JButton jButtonCerrarProcesoUtilidades;
protected JButton jButtonRecargarInformacionProcesoUtilidades;
protected JButton jButtonProcesarInformacionProcesoUtilidades;
protected JButton jButtonAnterioresProcesoUtilidades;
protected JButton jButtonSiguientesProcesoUtilidades;
protected JButton jButtonNuevoGuardarCambiosProcesoUtilidades;
//protected JButton jButtonGenerarReporteDinamicoProcesoUtilidades;
//protected JButton jButtonCerrarReporteDinamicoProcesoUtilidades;
//protected JButton jButtonGenerarExcelReporteDinamicoProcesoUtilidades;
//protected JButton jButtonAbrirImportacionProcesoUtilidades;
//protected JButton jButtonGenerarImportacionProcesoUtilidades;
//protected JButton jButtonCerrarImportacionProcesoUtilidades;
//protected JFileChooser jFileChooserImportacionProcesoUtilidades;
//protected File fileImportacionProcesoUtilidades;
//TOOLBAR
protected JButton jButtonNuevoToolBarProcesoUtilidades;
protected JButton jButtonDuplicarToolBarProcesoUtilidades;
protected JButton jButtonNuevoRelacionesToolBarProcesoUtilidades;
public JButton jButtonGuardarCambiosToolBarProcesoUtilidades;
protected JButton jButtonCopiarToolBarProcesoUtilidades;
protected JButton jButtonVerFormToolBarProcesoUtilidades;
public JButton jButtonGuardarCambiosTablaToolBarProcesoUtilidades;
protected JButton jButtonMostrarOcultarTablaToolBarProcesoUtilidades;
protected JButton jButtonCerrarToolBarProcesoUtilidades;
protected JButton jButtonRecargarInformacionToolBarProcesoUtilidades;
protected JButton jButtonProcesarInformacionToolBarProcesoUtilidades;
protected JButton jButtonAnterioresToolBarProcesoUtilidades;
protected JButton jButtonSiguientesToolBarProcesoUtilidades;
protected JButton jButtonNuevoGuardarCambiosToolBarProcesoUtilidades;
protected JButton jButtonAbrirOrderByToolBarProcesoUtilidades;
//TOOLBAR
//MENU
protected JMenuItem jMenuItemNuevoProcesoUtilidades;
protected JMenuItem jMenuItemDuplicarProcesoUtilidades;
protected JMenuItem jMenuItemNuevoRelacionesProcesoUtilidades;
protected JMenuItem jMenuItemGuardarCambiosProcesoUtilidades;
protected JMenuItem jMenuItemCopiarProcesoUtilidades;
protected JMenuItem jMenuItemVerFormProcesoUtilidades;
protected JMenuItem jMenuItemGuardarCambiosTablaProcesoUtilidades;
protected JMenuItem jMenuItemCerrarProcesoUtilidades;
protected JMenuItem jMenuItemDetalleCerrarProcesoUtilidades;
protected JMenuItem jMenuItemDetalleAbrirOrderByProcesoUtilidades;
protected JMenuItem jMenuItemDetalleMostarOcultarProcesoUtilidades;
protected JMenuItem jMenuItemRecargarInformacionProcesoUtilidades;
protected JMenuItem jMenuItemProcesarInformacionProcesoUtilidades;
protected JMenuItem jMenuItemAnterioresProcesoUtilidades;
protected JMenuItem jMenuItemSiguientesProcesoUtilidades;
protected JMenuItem jMenuItemNuevoGuardarCambiosProcesoUtilidades;
protected JMenuItem jMenuItemAbrirOrderByProcesoUtilidades;
protected JMenuItem jMenuItemMostrarOcultarProcesoUtilidades;
//MENU
protected JLabel jLabelAccionesProcesoUtilidades;
protected JCheckBox jCheckBoxSeleccionarTodosProcesoUtilidades;
protected JCheckBox jCheckBoxSeleccionadosProcesoUtilidades;
protected JCheckBox jCheckBoxConAltoMaximoTablaProcesoUtilidades;
protected JCheckBox jCheckBoxConGraficoReporteProcesoUtilidades;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposArchivosReportesProcesoUtilidades;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposReportesProcesoUtilidades;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxTiposReportesDinamicoProcesoUtilidades;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposGraficosReportesProcesoUtilidades;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposPaginacionProcesoUtilidades;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposRelacionesProcesoUtilidades;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposAccionesProcesoUtilidades;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposSeleccionarProcesoUtilidades;
protected JTextField jTextFieldValorCampoGeneralProcesoUtilidades;
//REPORTE DINAMICO
//@SuppressWarnings("rawtypes")
//public JLabel jLabelColumnasSelectReporteProcesoUtilidades;
//public JList<Reporte> jListColumnasSelectReporteProcesoUtilidades;
//public JScrollPane jScrollColumnasSelectReporteProcesoUtilidades;
//public JLabel jLabelRelacionesSelectReporteProcesoUtilidades;
//public JList<Reporte> jListRelacionesSelectReporteProcesoUtilidades;
//public JScrollPane jScrollRelacionesSelectReporteProcesoUtilidades;
//public JLabel jLabelConGraficoDinamicoProcesoUtilidades;
//protected JCheckBox jCheckBoxConGraficoDinamicoProcesoUtilidades;
//public JLabel jLabelGenerarExcelReporteDinamicoProcesoUtilidades;
//public JLabel jLabelTiposArchivoReporteDinamicoProcesoUtilidades;
//public JLabel jLabelArchivoImportacionProcesoUtilidades;
//public JLabel jLabelPathArchivoImportacionProcesoUtilidades;
//protected JTextField jTextFieldPathArchivoImportacionProcesoUtilidades;
//public JLabel jLabelColumnaCategoriaGraficoProcesoUtilidades;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxColumnaCategoriaGraficoProcesoUtilidades;
//public JLabel jLabelColumnaCategoriaValorProcesoUtilidades;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxColumnaCategoriaValorProcesoUtilidades;
//public JLabel jLabelColumnasValoresGraficoProcesoUtilidades;
//public JList<Reporte> jListColumnasValoresGraficoProcesoUtilidades;
//public JScrollPane jScrollColumnasValoresGraficoProcesoUtilidades;
//public JLabel jLabelTiposGraficosReportesDinamicoProcesoUtilidades;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxTiposGraficosReportesDinamicoProcesoUtilidades;
protected Boolean conMaximoRelaciones=true;
protected Boolean conFuncionalidadRelaciones=true;
public Boolean conCargarMinimo=false;
public Boolean cargarRelaciones=false;
public Boolean conMostrarAccionesCampo=false;
public Boolean permiteRecargarForm=false;//PARA NUEVO PREPARAR Y MANEJO DE EVENTOS, EVITAR QUE SE EJECUTE AL CARGAR VENTANA O LOAD
public Boolean conCargarFormDetalle=false;
//BYDAN_BUSQUEDAS
public JTabbedPane jTabbedPaneBusquedasProcesoUtilidades;
public JPanel jPanelBusquedaProcesoUtilidadesProcesoUtilidades;
public JButton jButtonBusquedaProcesoUtilidadesProcesoUtilidades;
public JPanel jPanelid_anioBusquedaProcesoUtilidadesProcesoUtilidades;
public JLabel jLabelid_anioBusquedaProcesoUtilidadesProcesoUtilidades;
@SuppressWarnings("rawtypes")
public JComboBox jComboBoxid_anioBusquedaProcesoUtilidadesProcesoUtilidades;
public JButton jButtonid_anioBusquedaProcesoUtilidadesProcesoUtilidades= new JButtonMe();
public JButton jButtonid_anioBusquedaProcesoUtilidadesProcesoUtilidadesUpdate= new JButtonMe();
public JButton jButtonid_anioBusquedaProcesoUtilidadesProcesoUtilidadesBusqueda= new JButtonMe();
public JPanel jPanelvalorBusquedaProcesoUtilidadesProcesoUtilidades;
public JLabel jLabelvalorBusquedaProcesoUtilidadesProcesoUtilidades;
public JTextField jTextFieldvalorBusquedaProcesoUtilidadesProcesoUtilidades;
public JButton jButtonvalorBusquedaProcesoUtilidadesProcesoUtilidadesBusqueda= new JButtonMe();
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
public static int openFrameCount = 0;
public static final int xOffset = 10, yOffset = 35;
//LOS DATOS DE NUEVO Y EDICION ACTUAL APARECEN EN OTRA VENTANA(true) O NO(false)
public static Boolean CON_DATOS_FRAME=true;
public static Boolean ISBINDING_MANUAL=true;
public static Boolean ISLOAD_FKLOTE=false;
public static Boolean ISBINDING_MANUAL_TABLA=true;
public static Boolean CON_CARGAR_MEMORIA_INICIAL=true;
//Al final no se utilizan, se inicializan desde JInternalFrameBase, desde ParametroGeneralUsuario
public static String STIPO_TAMANIO_GENERAL="NORMAL";
public static String STIPO_TAMANIO_GENERAL_TABLA="NORMAL";
public static Boolean CONTIPO_TAMANIO_MANUAL=false;
public static Boolean CON_LLAMADA_SIMPLE=true;
public static Boolean CON_LLAMADA_SIMPLE_TOTAL=true;
public static Boolean ESTA_CARGADO_PORPARTE=false;
public int iWidthScroll=0;//(screenSize.width-screenSize.width/2)+(250*0);
public int iHeightScroll=0;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//public int iWidthFormulario=450;//(screenSize.width-screenSize.width/2)+(250*0);
//public int iHeightFormulario=242;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//Esto va en DetalleForm
//public int iHeightFormularioMaximo=0;
//public int iWidthFormularioMaximo=0;
public int iWidthTableDefinicion=0;
public double dStart = 0;
public double dEnd = 0;
public double dDif = 0;
/*
double start=(double)System.currentTimeMillis();
double end=0;
double dif=0;
end=(double)System.currentTimeMillis();
dif=end - start;
start=(double)System.currentTimeMillis();
System.out.println("Tiempo(ms) Carga TEST 1_2 DetalleMovimientoInventario: " + dif);
*/
public SistemaParameterReturnGeneral sistemaReturnGeneral;
public List<Opcion> opcionsRelacionadas=new ArrayList<Opcion>();
//ES AUXILIAR PARA WINDOWS FORMS
public ProcesoUtilidadesJInternalFrame() throws Exception {
super(PaginaTipo.PRINCIPAL);
//super("ProcesoUtilidades No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
//Boolean cargarRelaciones=false;
initialize(null,false,false,false/*cargarRelaciones*/,null,null,null,null,null,null,PaginaTipo.PRINCIPAL);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public ProcesoUtilidadesJInternalFrame(Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("ProcesoUtilidades No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,paginaTipo);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public ProcesoUtilidadesJInternalFrame(Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("ProcesoUtilidades No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
initialize(null,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,null,null,null,null,null,null,paginaTipo);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public ProcesoUtilidadesJInternalFrame(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);//,jdesktopPane
this.jDesktopPane=jdesktopPane;
this.dStart=(double)System.currentTimeMillis();
//super("ProcesoUtilidades No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
long start_time=0;
long end_time=0;
if(Constantes2.ISDEVELOPING2) {
start_time = System.currentTimeMillis();
}
initialize(jdesktopPane,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo);
if(Constantes2.ISDEVELOPING2) {
end_time = System.currentTimeMillis();
String sTipo="Clase Padre Ventana";
Funciones2.getMensajeTiempoEjecucion(start_time, end_time, sTipo,false);
}
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public JInternalFrameBase getJInternalFrameParent() {
return jInternalFrameParent;
}
public void setJInternalFrameParent(JInternalFrameBase internalFrameParent) {
jInternalFrameParent = internalFrameParent;
}
public void setjButtonRecargarInformacion(JButton jButtonRecargarInformacionProcesoUtilidades) {
this.jButtonRecargarInformacionProcesoUtilidades = jButtonRecargarInformacionProcesoUtilidades;
}
public JButton getjButtonProcesarInformacionProcesoUtilidades() {
return this.jButtonProcesarInformacionProcesoUtilidades;
}
public void setjButtonProcesarInformacion(JButton jButtonProcesarInformacionProcesoUtilidades) {
this.jButtonProcesarInformacionProcesoUtilidades = jButtonProcesarInformacionProcesoUtilidades;
}
public JButton getjButtonRecargarInformacionProcesoUtilidades() {
return this.jButtonRecargarInformacionProcesoUtilidades;
}
public List<ProcesoUtilidades> getprocesoutilidadess() {
return this.procesoutilidadess;
}
public void setprocesoutilidadess(List<ProcesoUtilidades> procesoutilidadess) {
this.procesoutilidadess = procesoutilidadess;
}
public List<ProcesoUtilidades> getprocesoutilidadessAux() {
return this.procesoutilidadessAux;
}
public void setprocesoutilidadessAux(List<ProcesoUtilidades> procesoutilidadessAux) {
this.procesoutilidadessAux = procesoutilidadessAux;
}
public List<ProcesoUtilidades> getprocesoutilidadessEliminados() {
return this.procesoutilidadessEliminados;
}
public void setProcesoUtilidadessEliminados(List<ProcesoUtilidades> procesoutilidadessEliminados) {
this.procesoutilidadessEliminados = procesoutilidadessEliminados;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposSeleccionarProcesoUtilidades() {
return jComboBoxTiposSeleccionarProcesoUtilidades;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposSeleccionarProcesoUtilidades(
JComboBox jComboBoxTiposSeleccionarProcesoUtilidades) {
this.jComboBoxTiposSeleccionarProcesoUtilidades = jComboBoxTiposSeleccionarProcesoUtilidades;
}
public void setBorderResaltarTiposSeleccionarProcesoUtilidades() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
this.jComboBoxTiposSeleccionarProcesoUtilidades .setBorder(borderResaltar);
}
public JTextField getjTextFieldValorCampoGeneralProcesoUtilidades() {
return jTextFieldValorCampoGeneralProcesoUtilidades;
}
public void setjTextFieldValorCampoGeneralProcesoUtilidades(
JTextField jTextFieldValorCampoGeneralProcesoUtilidades) {
this.jTextFieldValorCampoGeneralProcesoUtilidades = jTextFieldValorCampoGeneralProcesoUtilidades;
}
public void setBorderResaltarValorCampoGeneralProcesoUtilidades() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
this.jTextFieldValorCampoGeneralProcesoUtilidades .setBorder(borderResaltar);
}
public JCheckBox getjCheckBoxSeleccionarTodosProcesoUtilidades() {
return this.jCheckBoxSeleccionarTodosProcesoUtilidades;
}
public void setjCheckBoxSeleccionarTodosProcesoUtilidades(
JCheckBox jCheckBoxSeleccionarTodosProcesoUtilidades) {
this.jCheckBoxSeleccionarTodosProcesoUtilidades = jCheckBoxSeleccionarTodosProcesoUtilidades;
}
public void setBorderResaltarSeleccionarTodosProcesoUtilidades() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
this.jCheckBoxSeleccionarTodosProcesoUtilidades .setBorder(borderResaltar);
}
public JCheckBox getjCheckBoxSeleccionadosProcesoUtilidades() {
return this.jCheckBoxSeleccionadosProcesoUtilidades;
}
public void setjCheckBoxSeleccionadosProcesoUtilidades(
JCheckBox jCheckBoxSeleccionadosProcesoUtilidades) {
this.jCheckBoxSeleccionadosProcesoUtilidades = jCheckBoxSeleccionadosProcesoUtilidades;
}
public void setBorderResaltarSeleccionadosProcesoUtilidades() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
this.jCheckBoxSeleccionadosProcesoUtilidades .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposArchivosReportesProcesoUtilidades() {
return this.jComboBoxTiposArchivosReportesProcesoUtilidades;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposArchivosReportesProcesoUtilidades(
JComboBox jComboBoxTiposArchivosReportesProcesoUtilidades) {
this.jComboBoxTiposArchivosReportesProcesoUtilidades = jComboBoxTiposArchivosReportesProcesoUtilidades;
}
public void setBorderResaltarTiposArchivosReportesProcesoUtilidades() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
this.jComboBoxTiposArchivosReportesProcesoUtilidades .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposReportesProcesoUtilidades() {
return this.jComboBoxTiposReportesProcesoUtilidades;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposReportesProcesoUtilidades(
JComboBox jComboBoxTiposReportesProcesoUtilidades) {
this.jComboBoxTiposReportesProcesoUtilidades = jComboBoxTiposReportesProcesoUtilidades;
}
//@SuppressWarnings("rawtypes")
//public JComboBox getjComboBoxTiposReportesDinamicoProcesoUtilidades() {
// return jComboBoxTiposReportesDinamicoProcesoUtilidades;
//}
//@SuppressWarnings("rawtypes")
//public void setjComboBoxTiposReportesDinamicoProcesoUtilidades(
// JComboBox jComboBoxTiposReportesDinamicoProcesoUtilidades) {
// this.jComboBoxTiposReportesDinamicoProcesoUtilidades = jComboBoxTiposReportesDinamicoProcesoUtilidades;
//}
//@SuppressWarnings("rawtypes")
//public JComboBox getjComboBoxTiposArchivosReportesDinamicoProcesoUtilidades() {
// return jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades;
//}
//@SuppressWarnings("rawtypes")
//public void setjComboBoxTiposArchivosReportesDinamicoProcesoUtilidades(
// JComboBox jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades) {
// this.jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades = jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades;
//}
public void setBorderResaltarTiposReportesProcesoUtilidades() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
this.jComboBoxTiposReportesProcesoUtilidades .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposGraficosReportesProcesoUtilidades() {
return this.jComboBoxTiposGraficosReportesProcesoUtilidades;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposGraficosReportesProcesoUtilidades(
JComboBox jComboBoxTiposGraficosReportesProcesoUtilidades) {
this.jComboBoxTiposGraficosReportesProcesoUtilidades = jComboBoxTiposGraficosReportesProcesoUtilidades;
}
public void setBorderResaltarTiposGraficosReportesProcesoUtilidades() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
this.jComboBoxTiposGraficosReportesProcesoUtilidades .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposPaginacionProcesoUtilidades() {
return this.jComboBoxTiposPaginacionProcesoUtilidades;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposPaginacionProcesoUtilidades(
JComboBox jComboBoxTiposPaginacionProcesoUtilidades) {
this.jComboBoxTiposPaginacionProcesoUtilidades = jComboBoxTiposPaginacionProcesoUtilidades;
}
public void setBorderResaltarTiposPaginacionProcesoUtilidades() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
this.jComboBoxTiposPaginacionProcesoUtilidades .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposRelacionesProcesoUtilidades() {
return this.jComboBoxTiposRelacionesProcesoUtilidades;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposAccionesProcesoUtilidades() {
return this.jComboBoxTiposAccionesProcesoUtilidades;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposRelacionesProcesoUtilidades(
JComboBox jComboBoxTiposRelacionesProcesoUtilidades) {
this.jComboBoxTiposRelacionesProcesoUtilidades = jComboBoxTiposRelacionesProcesoUtilidades;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposAccionesProcesoUtilidades(
JComboBox jComboBoxTiposAccionesProcesoUtilidades) {
this.jComboBoxTiposAccionesProcesoUtilidades = jComboBoxTiposAccionesProcesoUtilidades;
}
public void setBorderResaltarTiposRelacionesProcesoUtilidades() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
this.jComboBoxTiposRelacionesProcesoUtilidades .setBorder(borderResaltar);
}
public void setBorderResaltarTiposAccionesProcesoUtilidades() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
this.jComboBoxTiposAccionesProcesoUtilidades .setBorder(borderResaltar);
}
//public JCheckBox getjCheckBoxConGraficoDinamicoProcesoUtilidades() {
// return jCheckBoxConGraficoDinamicoProcesoUtilidades;
//}
//public void setjCheckBoxConGraficoDinamicoProcesoUtilidades(
// JCheckBox jCheckBoxConGraficoDinamicoProcesoUtilidades) {
// this.jCheckBoxConGraficoDinamicoProcesoUtilidades = jCheckBoxConGraficoDinamicoProcesoUtilidades;
//}
//public void setBorderResaltarConGraficoDinamicoProcesoUtilidades() {
// Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
// this.jTtoolBarProcesoUtilidades.setBorder(borderResaltar);
// this.jCheckBoxConGraficoDinamicoProcesoUtilidades .setBorder(borderResaltar);
//}
/*
public JDesktopPane getJDesktopPane() {
return jDesktopPane;
}
public void setJDesktopPane(JDesktopPane desktopPane) {
jDesktopPane = desktopPane;
}
*/
private void initialize(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
this.procesoutilidadesSessionBean=new ProcesoUtilidadesSessionBean();
this.procesoutilidadesSessionBean.setConGuardarRelaciones(conGuardarRelaciones);
this.procesoutilidadesSessionBean.setEsGuardarRelacionado(esGuardarRelacionado);
this.conCargarMinimo=this.procesoutilidadesSessionBean.getEsGuardarRelacionado();
this.cargarRelaciones=cargarRelaciones;
if(!this.conCargarMinimo) {
}
//this.sTipoTamanioGeneral=ProcesoUtilidadesJInternalFrame.STIPO_TAMANIO_GENERAL;
//this.sTipoTamanioGeneralTabla=ProcesoUtilidadesJInternalFrame.STIPO_TAMANIO_GENERAL_TABLA;
this.sTipoTamanioGeneral=FuncionesSwing.getTipoTamanioGeneral(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.sTipoTamanioGeneralTabla=FuncionesSwing.getTipoTamanioGeneralTabla(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.conTipoTamanioManual=FuncionesSwing.getConTipoTamanioManual(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.conTipoTamanioTodo=FuncionesSwing.getConTipoTamanioTodo(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
ProcesoUtilidadesJInternalFrame.STIPO_TAMANIO_GENERAL=this.sTipoTamanioGeneral;
ProcesoUtilidadesJInternalFrame.STIPO_TAMANIO_GENERAL_TABLA=this.sTipoTamanioGeneralTabla;
ProcesoUtilidadesJInternalFrame.CONTIPO_TAMANIO_MANUAL=this.conTipoTamanioManual;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int iWidth=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO);
int iHeight=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//this.setTitle(Funciones.GetTituloSistema(this.parametroGeneralSg,this.moduloActual,this.opcionActual,this.usuarioActual,"Proceso Utilidades MANTENIMIENTO"));
if(iWidth > 650) {
iWidth=650;
}
if(iHeight > 660) {
iHeight=660;
}
this.setSize(iWidth,iHeight);
this.setFrameIcon(new ImageIcon(FuncionesSwing.getImagenBackground(Constantes2.S_ICON_IMAGE)));
this.setContentPane(this.getJContentPane(iWidth,iHeight,jdesktopPane,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo));
if(!this.procesoutilidadesSessionBean.getEsGuardarRelacionado()) {
this.setResizable(true);
this.setClosable(true);
this.setMaximizable(true);
this.iconable=true;
setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
if(Constantes.CON_VARIAS_VENTANAS) {
openFrameCount++;
if(openFrameCount==Constantes.INUM_MAX_VENTANAS) {
openFrameCount=0;
}
}
}
ProcesoUtilidadesJInternalFrame.ESTA_CARGADO_PORPARTE=true;
//super("ProcesoUtilidades No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
//SwingUtilities.updateComponentTreeUI(this);
}
public void inicializarToolBar() {
this.jTtoolBarProcesoUtilidades= new JToolBar("MENU PRINCIPAL");
//TOOLBAR
//PRINCIPAL
this.jButtonNuevoToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonNuevoToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"nuevo","nuevo","Nuevo"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO"),"Nuevo",false);
this.jButtonNuevoGuardarCambiosToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonNuevoGuardarCambiosToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"nuevoguardarcambios","nuevoguardarcambios","Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"),"Nuevo",false);
this.jButtonGuardarCambiosTablaToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonGuardarCambiosTablaToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"guardarcambiostabla","guardarcambiostabla","Guardar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"),"Guardar",false);
this.jButtonDuplicarToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonDuplicarToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"duplicar","duplicar","Duplicar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("DUPLICAR"),"Duplicar",false);
this.jButtonCopiarToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonCopiarToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"copiar","copiar","Copiar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("COPIAR"),"Copiar",false);
this.jButtonVerFormToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonVerFormToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"ver_form","ver_form","Ver"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("VER_FORM"),"Ver",false);
this.jButtonRecargarInformacionToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonRecargarInformacionToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"recargar","recargar","Procesar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("RECARGAR"),"Procesar",false);
this.jButtonAnterioresToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonRecargarInformacionToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"anteriores","anteriores","Anteriores Datos" + FuncionesSwing.getKeyMensaje("ANTERIORES"),"<<",false);
this.jButtonSiguientesToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonRecargarInformacionToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"siguientes","siguientes","Siguientes Datos" + FuncionesSwing.getKeyMensaje("SIGUIENTES"),">>",false);
this.jButtonAbrirOrderByToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonAbrirOrderByToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"orden","orden","Orden" + FuncionesSwing.getKeyMensaje("ORDEN"),"Orden",false);
this.jButtonNuevoRelacionesToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonNuevoRelacionesToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"nuevo_relaciones","nuevo_relaciones","NUEVO RELACIONES" + FuncionesSwing.getKeyMensaje("NUEVO_RELACIONES"),"NUEVO RELACIONES",false);
this.jButtonMostrarOcultarTablaToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonMostrarOcultarTablaToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"mostrar_ocultar","mostrar_ocultar","Mostrar Ocultar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"),"Mostrar Ocultar",false);
this.jButtonCerrarToolBarProcesoUtilidades=FuncionesSwing.getButtonToolBarGeneral(this.jButtonCerrarToolBarProcesoUtilidades,this.jTtoolBarProcesoUtilidades,
"cerrar","cerrar","Salir"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CERRAR"),"Salir",false);
//this.jButtonNuevoRelacionesToolBarProcesoUtilidades=new JButtonMe();
//protected JButton jButtonNuevoRelacionesToolBarProcesoUtilidades;
this.jButtonProcesarInformacionToolBarProcesoUtilidades=new JButtonMe();
//protected JButton jButtonProcesarInformacionToolBarProcesoUtilidades;
//protected JButton jButtonModificarToolBarProcesoUtilidades;
//PRINCIPAL
//DETALLE
//DETALLE_FIN
}
public void cargarMenus() {
this.jmenuBarProcesoUtilidades=new JMenuBarMe();
//PRINCIPAL
this.jmenuProcesoUtilidades=new JMenuMe("General");
this.jmenuArchivoProcesoUtilidades=new JMenuMe("Archivo");
this.jmenuAccionesProcesoUtilidades=new JMenuMe("Acciones");
this.jmenuDatosProcesoUtilidades=new JMenuMe("Datos");
//PRINCIPAL_FIN
//DETALLE
//DETALLE_FIN
this.jMenuItemNuevoProcesoUtilidades= new JMenuItem("Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jMenuItemNuevoProcesoUtilidades.setActionCommand("Nuevo");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoProcesoUtilidades,"nuevo_button","Nuevo");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDuplicarProcesoUtilidades= new JMenuItem("Duplicar" + FuncionesSwing.getKeyMensaje("DUPLICAR"));
this.jMenuItemDuplicarProcesoUtilidades.setActionCommand("Duplicar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDuplicarProcesoUtilidades,"duplicar_button","Duplicar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDuplicarProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemNuevoRelacionesProcesoUtilidades= new JMenuItem("Nuevo Rel" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"));
this.jMenuItemNuevoRelacionesProcesoUtilidades.setActionCommand("Nuevo Rel");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoRelacionesProcesoUtilidades,"nuevorelaciones_button","Nuevo Rel");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoRelacionesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemGuardarCambiosProcesoUtilidades= new JMenuItem("Guardar" + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jMenuItemGuardarCambiosProcesoUtilidades.setActionCommand("Guardar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemGuardarCambiosProcesoUtilidades,"guardarcambios_button","Guardar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemGuardarCambiosProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCopiarProcesoUtilidades= new JMenuItem("Copiar" + FuncionesSwing.getKeyMensaje("COPIAR"));
this.jMenuItemCopiarProcesoUtilidades.setActionCommand("Copiar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCopiarProcesoUtilidades,"copiar_button","Copiar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCopiarProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemVerFormProcesoUtilidades= new JMenuItem("Ver" + FuncionesSwing.getKeyMensaje("VER_FORM"));
this.jMenuItemVerFormProcesoUtilidades.setActionCommand("Ver");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemVerFormProcesoUtilidades,"ver_form_button","Ver");
FuncionesSwing.setBoldMenuItem(this.jMenuItemVerFormProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemGuardarCambiosTablaProcesoUtilidades= new JMenuItem("Guardar Tabla" + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jMenuItemGuardarCambiosTablaProcesoUtilidades.setActionCommand("Guardar Tabla");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemGuardarCambiosTablaProcesoUtilidades,"guardarcambiostabla_button","Guardar Tabla");
FuncionesSwing.setBoldMenuItem(this.jMenuItemGuardarCambiosTablaProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCerrarProcesoUtilidades= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR"));
this.jMenuItemCerrarProcesoUtilidades.setActionCommand("Cerrar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCerrarProcesoUtilidades,"cerrar_button","Salir");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCerrarProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemRecargarInformacionProcesoUtilidades= new JMenuItem("Recargar" + FuncionesSwing.getKeyMensaje("RECARGAR"));
this.jMenuItemRecargarInformacionProcesoUtilidades.setActionCommand("Recargar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemRecargarInformacionProcesoUtilidades,"recargar_button","Recargar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemRecargarInformacionProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemProcesarInformacionProcesoUtilidades= new JMenuItem("Procesar Informacion");
this.jMenuItemProcesarInformacionProcesoUtilidades.setActionCommand("Procesar Informacion");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemProcesarInformacionProcesoUtilidades,"procesar_button","Procesar Informacion");
this.jMenuItemAnterioresProcesoUtilidades= new JMenuItem("Anteriores" + FuncionesSwing.getKeyMensaje("ANTERIORES"));
this.jMenuItemAnterioresProcesoUtilidades.setActionCommand("Anteriores");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemAnterioresProcesoUtilidades,"anteriores_button","Anteriores");
FuncionesSwing.setBoldMenuItem(this.jMenuItemAnterioresProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemSiguientesProcesoUtilidades= new JMenuItem("Siguientes" + FuncionesSwing.getKeyMensaje("SIGUIENTES"));
this.jMenuItemSiguientesProcesoUtilidades.setActionCommand("Siguientes");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemSiguientesProcesoUtilidades,"siguientes_button","Siguientes");
FuncionesSwing.setBoldMenuItem(this.jMenuItemSiguientesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemAbrirOrderByProcesoUtilidades= new JMenuItem("Orden" + FuncionesSwing.getKeyMensaje("ORDEN"));
this.jMenuItemAbrirOrderByProcesoUtilidades.setActionCommand("Orden");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemAbrirOrderByProcesoUtilidades,"orden_button","Orden");
FuncionesSwing.setBoldMenuItem(this.jMenuItemAbrirOrderByProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemMostrarOcultarProcesoUtilidades= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemMostrarOcultarProcesoUtilidades.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemMostrarOcultarProcesoUtilidades,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemMostrarOcultarProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleAbrirOrderByProcesoUtilidades= new JMenuItem("Orden" + FuncionesSwing.getKeyMensaje("ORDEN"));
this.jMenuItemDetalleAbrirOrderByProcesoUtilidades.setActionCommand("Orden");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleAbrirOrderByProcesoUtilidades,"orden_button","Orden");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleAbrirOrderByProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleMostarOcultarProcesoUtilidades= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemDetalleMostarOcultarProcesoUtilidades.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleMostarOcultarProcesoUtilidades,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleMostarOcultarProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemNuevoGuardarCambiosProcesoUtilidades= new JMenuItem("Nuevo Tabla" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"));
this.jMenuItemNuevoGuardarCambiosProcesoUtilidades.setActionCommand("Nuevo Tabla");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoGuardarCambiosProcesoUtilidades,"nuevoguardarcambios_button","Nuevo");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoGuardarCambiosProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
//PRINCIPAL
if(!this.conCargarMinimo) {
this.jmenuArchivoProcesoUtilidades.add(this.jMenuItemCerrarProcesoUtilidades);
this.jmenuAccionesProcesoUtilidades.add(this.jMenuItemNuevoProcesoUtilidades);
this.jmenuAccionesProcesoUtilidades.add(this.jMenuItemNuevoGuardarCambiosProcesoUtilidades);
this.jmenuAccionesProcesoUtilidades.add(this.jMenuItemNuevoRelacionesProcesoUtilidades);
this.jmenuAccionesProcesoUtilidades.add(this.jMenuItemGuardarCambiosTablaProcesoUtilidades);
this.jmenuAccionesProcesoUtilidades.add(this.jMenuItemDuplicarProcesoUtilidades);
this.jmenuAccionesProcesoUtilidades.add(this.jMenuItemCopiarProcesoUtilidades);
this.jmenuAccionesProcesoUtilidades.add(this.jMenuItemVerFormProcesoUtilidades);
this.jmenuDatosProcesoUtilidades.add(this.jMenuItemRecargarInformacionProcesoUtilidades);
this.jmenuDatosProcesoUtilidades.add(this.jMenuItemAnterioresProcesoUtilidades);
this.jmenuDatosProcesoUtilidades.add(this.jMenuItemSiguientesProcesoUtilidades);
this.jmenuDatosProcesoUtilidades.add(this.jMenuItemAbrirOrderByProcesoUtilidades);
this.jmenuDatosProcesoUtilidades.add(this.jMenuItemMostrarOcultarProcesoUtilidades);
}
//PRINCIPAL_FIN
//DETALLE
//this.jmenuDetalleAccionesProcesoUtilidades.add(this.jMenuItemGuardarCambiosProcesoUtilidades);
//DETALLE_FIN
//RELACIONES
//RELACIONES
//PRINCIPAL
if(!this.conCargarMinimo) {
FuncionesSwing.setBoldMenu(this.jmenuArchivoProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuAccionesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuDatosProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jmenuBarProcesoUtilidades.add(this.jmenuArchivoProcesoUtilidades);
this.jmenuBarProcesoUtilidades.add(this.jmenuAccionesProcesoUtilidades);
this.jmenuBarProcesoUtilidades.add(this.jmenuDatosProcesoUtilidades);
}
//PRINCIPAL_FIN
//DETALLE
//DETALLE_FIN
//AGREGA MENU A PANTALLA
if(!this.conCargarMinimo) {
this.setJMenuBar(this.jmenuBarProcesoUtilidades);
}
//AGREGA MENU DETALLE A PANTALLA
}
public void inicializarElementosBusquedasProcesoUtilidades() {
//BYDAN_BUSQUEDAS
//INDICES BUSQUEDA
this.jPanelBusquedaProcesoUtilidadesProcesoUtilidades=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelBusquedaProcesoUtilidadesProcesoUtilidades.setToolTipText("Procesar Proceso Utilidades");
this.jButtonBusquedaProcesoUtilidadesProcesoUtilidades= new JButtonMe();
this.jButtonBusquedaProcesoUtilidadesProcesoUtilidades.setText("Procesar");
this.jButtonBusquedaProcesoUtilidadesProcesoUtilidades.setToolTipText("Procesar Proceso Utilidades");
FuncionesSwing.addImagenButtonGeneral(this.jButtonBusquedaProcesoUtilidadesProcesoUtilidades,"buscar_button","Procesar Proceso Utilidades");
FuncionesSwing.setBoldButton(this.jButtonBusquedaProcesoUtilidadesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
jLabelid_anioBusquedaProcesoUtilidadesProcesoUtilidades = new JLabelMe();
jLabelid_anioBusquedaProcesoUtilidadesProcesoUtilidades.setText("Anio :");
jLabelid_anioBusquedaProcesoUtilidadesProcesoUtilidades.setToolTipText("Anio");
jLabelid_anioBusquedaProcesoUtilidadesProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL));
jLabelid_anioBusquedaProcesoUtilidadesProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL));
jLabelid_anioBusquedaProcesoUtilidadesProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL));
FuncionesSwing.setBoldLabel(jLabelid_anioBusquedaProcesoUtilidadesProcesoUtilidades,STIPO_TAMANIO_GENERAL,false,true,this);
jComboBoxid_anioBusquedaProcesoUtilidadesProcesoUtilidades= new JComboBoxMe();
jComboBoxid_anioBusquedaProcesoUtilidadesProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jComboBoxid_anioBusquedaProcesoUtilidadesProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jComboBoxid_anioBusquedaProcesoUtilidadesProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
FuncionesSwing.setBoldComboBox(jComboBoxid_anioBusquedaProcesoUtilidadesProcesoUtilidades,STIPO_TAMANIO_GENERAL,false,true,this);
jLabelvalorBusquedaProcesoUtilidadesProcesoUtilidades = new JLabelMe();
jLabelvalorBusquedaProcesoUtilidadesProcesoUtilidades.setText("Valor :");
jLabelvalorBusquedaProcesoUtilidadesProcesoUtilidades.setToolTipText("Valor");
jLabelvalorBusquedaProcesoUtilidadesProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL));
jLabelvalorBusquedaProcesoUtilidadesProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL));
jLabelvalorBusquedaProcesoUtilidadesProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL));
FuncionesSwing.setBoldLabel(jLabelvalorBusquedaProcesoUtilidadesProcesoUtilidades,STIPO_TAMANIO_GENERAL,false,true,this);
jTextFieldvalorBusquedaProcesoUtilidadesProcesoUtilidades= new JTextFieldMe();
jTextFieldvalorBusquedaProcesoUtilidadesProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jTextFieldvalorBusquedaProcesoUtilidadesProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jTextFieldvalorBusquedaProcesoUtilidadesProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
FuncionesSwing.setBoldTextField(jTextFieldvalorBusquedaProcesoUtilidadesProcesoUtilidades,STIPO_TAMANIO_GENERAL,false,true,this);
jTextFieldvalorBusquedaProcesoUtilidadesProcesoUtilidades.setText("0.0");
this.jTabbedPaneBusquedasProcesoUtilidades=new JTabbedPane();
this.jTabbedPaneBusquedasProcesoUtilidades.setMinimumSize(new Dimension(this.getWidth(),Constantes.ISWING_ALTO_TABPANE_BUSQUEDA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_TABPANE_BUSQUEDA,25)));
this.jTabbedPaneBusquedasProcesoUtilidades.setMaximumSize(new Dimension(this.getWidth(),Constantes.ISWING_ALTO_TABPANE_BUSQUEDA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_TABPANE_BUSQUEDA,25)));
this.jTabbedPaneBusquedasProcesoUtilidades.setPreferredSize(new Dimension(this.getWidth(),Constantes.ISWING_ALTO_TABPANE_BUSQUEDA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_TABPANE_BUSQUEDA,25)));
//this.jTabbedPaneBusquedasProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Proceso Utilidades"));
this.jTabbedPaneBusquedasProcesoUtilidades.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
FuncionesSwing.setBoldTabbedPane(this.jTabbedPaneBusquedasProcesoUtilidades,STIPO_TAMANIO_GENERAL,false,true,this);
//INDICES BUSQUEDA_FIN
}
//JPanel
//@SuppressWarnings({"unchecked" })//"rawtypes"
public JScrollPane getJContentPane(int iWidth,int iHeight,JDesktopPane jDesktopPane,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
//PARA TABLA PARAMETROS
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
this.jContentPane = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.usuarioActual=usuarioActual;
this.resumenUsuarioActual=resumenUsuarioActual;
this.opcionActual=opcionActual;
this.moduloActual=moduloActual;
this.parametroGeneralSg=parametroGeneralSg;
this.parametroGeneralUsuario=parametroGeneralUsuario;
this.jDesktopPane=jDesktopPane;
this.conFuncionalidadRelaciones=parametroGeneralUsuario.getcon_guardar_relaciones();
int iGridyPrincipal=0;
this.inicializarToolBar();
//CARGAR MENUS
if(this.conCargarFormDetalle) { //true) {
//this.jInternalFrameDetalleProcesoUtilidades = new ProcesoUtilidadesDetalleJInternalFrame(paginaTipo);//JInternalFrameBase("Proceso Utilidades DATOS");
this.jInternalFrameDetalleFormProcesoUtilidades = new ProcesoUtilidadesDetalleFormJInternalFrame(jDesktopPane,this.procesoutilidadesSessionBean.getConGuardarRelaciones(),this.procesoutilidadesSessionBean.getEsGuardarRelacionado(),cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo);
} else {
this.jInternalFrameDetalleFormProcesoUtilidades = null;//new ProcesoUtilidadesDetalleFormJInternalFrame("MINIMO");
}
this.cargarMenus();
this.gridaBagLayoutProcesoUtilidades= new GridBagLayout();
this.jTableDatosProcesoUtilidades = new JTableMe();
String sToolTipProcesoUtilidades="";
sToolTipProcesoUtilidades=ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO;
if(Constantes.ISDEVELOPING) {
sToolTipProcesoUtilidades+="(Nomina.ProcesoUtilidades)";
}
if(!this.procesoutilidadesSessionBean.getEsGuardarRelacionado()) {
sToolTipProcesoUtilidades+="_"+this.opcionActual.getId();
}
this.jTableDatosProcesoUtilidades.setToolTipText(sToolTipProcesoUtilidades);
//SE DEFINE EN DETALLE
//FuncionesSwing.setBoldLabelTable(this.jTableDatosProcesoUtilidades);
this.jTableDatosProcesoUtilidades.setAutoCreateRowSorter(true);
this.jTableDatosProcesoUtilidades.setRowHeight(Constantes.ISWING_ALTO_FILA_TABLA + Constantes.ISWING_ALTO_FILA_TABLA_EXTRA_FECHA);
//MULTIPLE SELECTION
this.jTableDatosProcesoUtilidades.setRowSelectionAllowed(true);
this.jTableDatosProcesoUtilidades.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
FuncionesSwing.setBoldTable(jTableDatosProcesoUtilidades,STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonNuevoProcesoUtilidades = new JButtonMe();
this.jButtonDuplicarProcesoUtilidades = new JButtonMe();
this.jButtonCopiarProcesoUtilidades = new JButtonMe();
this.jButtonVerFormProcesoUtilidades = new JButtonMe();
this.jButtonNuevoRelacionesProcesoUtilidades = new JButtonMe();
this.jButtonGuardarCambiosTablaProcesoUtilidades = new JButtonMe();
this.jButtonCerrarProcesoUtilidades = new JButtonMe();
this.jScrollPanelDatosProcesoUtilidades = new JScrollPane();
this.jScrollPanelDatosGeneralProcesoUtilidades = new JScrollPane();
this.jPanelAccionesProcesoUtilidades = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
//if(!this.conCargarMinimo) {
;
//}
this.sPath=" <---> Acceso: Proceso Utilidades";
if(!this.procesoutilidadesSessionBean.getEsGuardarRelacionado()) {
this.jScrollPanelDatosProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Proceso Utilidadeses" + this.sPath));
} else {
this.jScrollPanelDatosProcesoUtilidades.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
}
this.jScrollPanelDatosGeneralProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos"));
this.jPanelAccionesProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));
this.jPanelAccionesProcesoUtilidades.setToolTipText("Acciones");
this.jPanelAccionesProcesoUtilidades.setName("Acciones");
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosGeneralProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,false,this);
//if(!this.conCargarMinimo) {
;
//}
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
if(!this.conCargarMinimo) {
//REPORTE DINAMICO
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameReporteDinamicoProcesoUtilidades=new ReporteDinamicoJInternalFrame(ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO,this);
//this.cargarReporteDinamicoProcesoUtilidades();
//IMPORTACION
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameImportacionProcesoUtilidades=new ImportacionJInternalFrame(ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO,this);
//this.cargarImportacionProcesoUtilidades();
}
String sMapKey = "";
InputMap inputMap =null;
this.jButtonAbrirOrderByProcesoUtilidades = new JButtonMe();
this.jButtonAbrirOrderByProcesoUtilidades.setText("Orden");
this.jButtonAbrirOrderByProcesoUtilidades.setToolTipText("Orden"+FuncionesSwing.getKeyMensaje("ORDEN"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonAbrirOrderByProcesoUtilidades,"orden_button","Orden");
FuncionesSwing.setBoldButton(this.jButtonAbrirOrderByProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
sMapKey = "AbrirOrderBySistema";
inputMap = this.jButtonAbrirOrderByProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ORDEN") , FuncionesSwing.getMaskKey("ORDEN")), sMapKey);
this.jButtonAbrirOrderByProcesoUtilidades.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"AbrirOrderBySistema"));
if(!this.conCargarMinimo) {
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameOrderByProcesoUtilidades=new OrderByJInternalFrame(STIPO_TAMANIO_GENERAL,this.jButtonAbrirOrderByProcesoUtilidades,false,this);
//this.cargarOrderByProcesoUtilidades(false);
} else {
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameOrderByProcesoUtilidades=new OrderByJInternalFrame(STIPO_TAMANIO_GENERAL,this.jButtonAbrirOrderByProcesoUtilidades,true,this);
//this.cargarOrderByProcesoUtilidades(true);
}
//VALORES PARA DISENO
/*
this.jTableDatosProcesoUtilidades.setMinimumSize(new Dimension(400,50));//430
this.jTableDatosProcesoUtilidades.setMaximumSize(new Dimension(400,50));//430
this.jTableDatosProcesoUtilidades.setPreferredSize(new Dimension(400,50));//430
this.jScrollPanelDatosProcesoUtilidades.setMinimumSize(new Dimension(400,50));
this.jScrollPanelDatosProcesoUtilidades.setMaximumSize(new Dimension(400,50));
this.jScrollPanelDatosProcesoUtilidades.setPreferredSize(new Dimension(400,50));
*/
this.jButtonNuevoProcesoUtilidades.setText("Nuevo");
this.jButtonDuplicarProcesoUtilidades.setText("Duplicar");
this.jButtonCopiarProcesoUtilidades.setText("Copiar");
this.jButtonVerFormProcesoUtilidades.setText("Ver");
this.jButtonNuevoRelacionesProcesoUtilidades.setText("Nuevo Rel");
this.jButtonGuardarCambiosTablaProcesoUtilidades.setText("Guardar");
this.jButtonCerrarProcesoUtilidades.setText("Salir");
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoProcesoUtilidades,"nuevo_button","Nuevo",this.procesoutilidadesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonDuplicarProcesoUtilidades,"duplicar_button","Duplicar",this.procesoutilidadesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCopiarProcesoUtilidades,"copiar_button","Copiar",this.procesoutilidadesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonVerFormProcesoUtilidades,"ver_form","Ver",this.procesoutilidadesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoRelacionesProcesoUtilidades,"nuevorelaciones_button","Nuevo Rel",this.procesoutilidadesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosTablaProcesoUtilidades,"guardarcambiostabla_button","Guardar",this.procesoutilidadesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarProcesoUtilidades,"cerrar_button","Salir",this.procesoutilidadesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.setBoldButton(this.jButtonNuevoProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonDuplicarProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonCopiarProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonVerFormProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonNuevoRelacionesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosTablaProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonCerrarProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonNuevoProcesoUtilidades.setToolTipText("Nuevo"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jButtonDuplicarProcesoUtilidades.setToolTipText("Duplicar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("DUPLICAR"));
this.jButtonCopiarProcesoUtilidades.setToolTipText("Copiar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO+ FuncionesSwing.getKeyMensaje("COPIAR"));
this.jButtonVerFormProcesoUtilidades.setToolTipText("Ver"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO+ FuncionesSwing.getKeyMensaje("VER_FORM"));
this.jButtonNuevoRelacionesProcesoUtilidades.setToolTipText("Nuevo Rel"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO_RELACIONES"));
this.jButtonGuardarCambiosTablaProcesoUtilidades.setToolTipText("Guardar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jButtonCerrarProcesoUtilidades.setToolTipText("Salir"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CERRAR"));
//HOT KEYS
/*
N->Nuevo
N->Alt + Nuevo Relaciones (ANTES R)
A->Actualizar
E->Eliminar
S->Cerrar
C->->Mayus + Cancelar (ANTES Q->Quit)
G->Guardar Cambios
D->Duplicar
C->Alt + Cop?ar
O->Orden
N->Nuevo Tabla
R->Recargar Informacion Inicial (ANTES I)
Alt + Pag.Down->Siguientes
Alt + Pag.Up->Anteriores
NO UTILIZADOS
M->Modificar
*/
//String sMapKey = "";
//InputMap inputMap =null;
//NUEVO
sMapKey = "NuevoProcesoUtilidades";
inputMap = this.jButtonNuevoProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO") , FuncionesSwing.getMaskKey("NUEVO")), sMapKey);
this.jButtonNuevoProcesoUtilidades.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"NuevoProcesoUtilidades"));
//DUPLICAR
sMapKey = "DuplicarProcesoUtilidades";
inputMap = this.jButtonDuplicarProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("DUPLICAR") , FuncionesSwing.getMaskKey("DUPLICAR")), sMapKey);
this.jButtonDuplicarProcesoUtilidades.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"DuplicarProcesoUtilidades"));
//COPIAR
sMapKey = "CopiarProcesoUtilidades";
inputMap = this.jButtonCopiarProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("COPIAR") , FuncionesSwing.getMaskKey("COPIAR")), sMapKey);
this.jButtonCopiarProcesoUtilidades.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"CopiarProcesoUtilidades"));
//VEr FORM
sMapKey = "VerFormProcesoUtilidades";
inputMap = this.jButtonVerFormProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("VER_FORM") , FuncionesSwing.getMaskKey("VER_FORM")), sMapKey);
this.jButtonVerFormProcesoUtilidades.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"VerFormProcesoUtilidades"));
//NUEVO RELACIONES
sMapKey = "NuevoRelacionesProcesoUtilidades";
inputMap = this.jButtonNuevoRelacionesProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO_RELACIONES") , FuncionesSwing.getMaskKey("NUEVO_RELACIONES")), sMapKey);
this.jButtonNuevoRelacionesProcesoUtilidades.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"NuevoRelacionesProcesoUtilidades"));
//MODIFICAR
/*
sMapKey = "ModificarProcesoUtilidades";
inputMap = this.jButtonModificarProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("MODIFICAR") , FuncionesSwing.getMaskKey("MODIFICAR")), sMapKey);
this.jButtonModificarProcesoUtilidades.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"ModificarProcesoUtilidades"));
*/
//CERRAR
sMapKey = "CerrarProcesoUtilidades";
inputMap = this.jButtonCerrarProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CERRAR") , FuncionesSwing.getMaskKey("CERRAR")), sMapKey);
this.jButtonCerrarProcesoUtilidades.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CerrarProcesoUtilidades"));
//GUARDAR CAMBIOS
sMapKey = "GuardarCambiosTablaProcesoUtilidades";
inputMap = this.jButtonGuardarCambiosTablaProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("GUARDAR_CAMBIOS") , FuncionesSwing.getMaskKey("GUARDAR_CAMBIOS")), sMapKey);
this.jButtonGuardarCambiosTablaProcesoUtilidades.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"GuardarCambiosTablaProcesoUtilidades"));
//ABRIR ORDER BY
if(!this.conCargarMinimo) {
}
//HOT KEYS
this.jPanelParametrosReportesProcesoUtilidades = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosReportesAccionesProcesoUtilidades = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelPaginacionProcesoUtilidades = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar1ProcesoUtilidades= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar2ProcesoUtilidades= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar3ProcesoUtilidades= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar4ProcesoUtilidades= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
//this.jPanelParametrosAuxiliar5ProcesoUtilidades= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosReportesProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Parametros Reportes-Acciones"));
this.jPanelParametrosReportesProcesoUtilidades.setName("jPanelParametrosReportesProcesoUtilidades");
this.jPanelParametrosReportesAccionesProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Parametros Acciones"));
//this.jPanelParametrosReportesAccionesProcesoUtilidades.setBorder(javax.swing.BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
this.jPanelParametrosReportesAccionesProcesoUtilidades.setName("jPanelParametrosReportesAccionesProcesoUtilidades");
FuncionesSwing.setBoldPanel(this.jPanelParametrosReportesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelParametrosReportesAccionesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonRecargarInformacionProcesoUtilidades = new JButtonMe();
this.jButtonRecargarInformacionProcesoUtilidades.setText("Procesar");
this.jButtonRecargarInformacionProcesoUtilidades.setToolTipText("Procesar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("RECARGAR"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonRecargarInformacionProcesoUtilidades,"recargar_button","Procesar");
this.jButtonRecargarInformacionProcesoUtilidades.setVisible(false);
this.jButtonProcesarInformacionProcesoUtilidades = new JButtonMe();
this.jButtonProcesarInformacionProcesoUtilidades.setText("Procesar");
this.jButtonProcesarInformacionProcesoUtilidades.setToolTipText("Procesar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO);
this.jButtonProcesarInformacionProcesoUtilidades.setVisible(false);
this.jButtonProcesarInformacionProcesoUtilidades.setMinimumSize(new Dimension(185,25));
this.jButtonProcesarInformacionProcesoUtilidades.setMaximumSize(new Dimension(185,25));
this.jButtonProcesarInformacionProcesoUtilidades.setPreferredSize(new Dimension(185,25));
this.jComboBoxTiposArchivosReportesProcesoUtilidades = new JComboBoxMe();
//this.jComboBoxTiposArchivosReportesProcesoUtilidades.setText("TIPO");
this.jComboBoxTiposArchivosReportesProcesoUtilidades.setToolTipText("Tipos De Archivo");
this.jComboBoxTiposReportesProcesoUtilidades = new JComboBoxMe();
//this.jComboBoxTiposArchivosReportesProcesoUtilidades.setText("TIPO");
this.jComboBoxTiposReportesProcesoUtilidades.setToolTipText("Tipos De Reporte");
this.jComboBoxTiposGraficosReportesProcesoUtilidades = new JComboBoxMe();
//this.jComboBoxTiposArchivosReportesProcesoUtilidades.setText("TIPO");
this.jComboBoxTiposGraficosReportesProcesoUtilidades.setToolTipText("Tipos De Reporte");
this.jComboBoxTiposPaginacionProcesoUtilidades = new JComboBoxMe();
//this.jComboBoxTiposPaginacionProcesoUtilidades.setText("Paginacion");
this.jComboBoxTiposPaginacionProcesoUtilidades.setToolTipText("Tipos De Paginacion");
this.jComboBoxTiposRelacionesProcesoUtilidades = new JComboBoxMe();
//this.jComboBoxTiposRelacionesProcesoUtilidades.setText("Accion");
this.jComboBoxTiposRelacionesProcesoUtilidades.setToolTipText("Tipos de Relaciones");
this.jComboBoxTiposAccionesProcesoUtilidades = new JComboBoxMe();
//this.jComboBoxTiposAccionesProcesoUtilidades.setText("Accion");
this.jComboBoxTiposAccionesProcesoUtilidades.setToolTipText("Tipos de Acciones");
this.jComboBoxTiposSeleccionarProcesoUtilidades = new JComboBoxMe();
//this.jComboBoxTiposSeleccionarProcesoUtilidades.setText("Accion");
this.jComboBoxTiposSeleccionarProcesoUtilidades.setToolTipText("Tipos de Seleccion");
this.jTextFieldValorCampoGeneralProcesoUtilidades=new JTextFieldMe();
this.jTextFieldValorCampoGeneralProcesoUtilidades.setMinimumSize(new Dimension(100,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldValorCampoGeneralProcesoUtilidades.setMaximumSize(new Dimension(100,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldValorCampoGeneralProcesoUtilidades.setPreferredSize(new Dimension(100,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesProcesoUtilidades = new JLabelMe();
this.jLabelAccionesProcesoUtilidades.setText("Acciones");
this.jLabelAccionesProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jCheckBoxSeleccionarTodosProcesoUtilidades = new JCheckBoxMe();
this.jCheckBoxSeleccionarTodosProcesoUtilidades.setText("Sel. Todos");
this.jCheckBoxSeleccionarTodosProcesoUtilidades.setToolTipText("Sel. Todos");
this.jCheckBoxSeleccionadosProcesoUtilidades = new JCheckBoxMe();
//this.jCheckBoxSeleccionadosProcesoUtilidades.setText("Seleccionados");
this.jCheckBoxSeleccionadosProcesoUtilidades.setToolTipText("SELECCIONAR SELECCIONADOS");
this.jCheckBoxConAltoMaximoTablaProcesoUtilidades = new JCheckBoxMe();
//this.jCheckBoxConAltoMaximoTablaProcesoUtilidades.setText("Con Maximo Alto Tabla");
this.jCheckBoxConAltoMaximoTablaProcesoUtilidades.setToolTipText("Con Maximo Alto Tabla");
this.jCheckBoxConGraficoReporteProcesoUtilidades = new JCheckBoxMe();
this.jCheckBoxConGraficoReporteProcesoUtilidades.setText("Graf.");
this.jCheckBoxConGraficoReporteProcesoUtilidades.setToolTipText("Con Grafico");
this.jButtonAnterioresProcesoUtilidades = new JButtonMe();
//this.jButtonAnterioresProcesoUtilidades.setText("<<");
this.jButtonAnterioresProcesoUtilidades.setToolTipText("Anteriores Datos" + FuncionesSwing.getKeyMensaje("ANTERIORES"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonAnterioresProcesoUtilidades,"anteriores_button","<<");
FuncionesSwing.setBoldButton(this.jButtonAnterioresProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonSiguientesProcesoUtilidades = new JButtonMe();
//this.jButtonSiguientesProcesoUtilidades.setText(">>");
this.jButtonSiguientesProcesoUtilidades.setToolTipText("Siguientes Datos" + FuncionesSwing.getKeyMensaje("SIGUIENTES"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonSiguientesProcesoUtilidades,"siguientes_button",">>");
FuncionesSwing.setBoldButton(this.jButtonSiguientesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonNuevoGuardarCambiosProcesoUtilidades = new JButtonMe();
this.jButtonNuevoGuardarCambiosProcesoUtilidades.setText("Nue");
this.jButtonNuevoGuardarCambiosProcesoUtilidades.setToolTipText("Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoGuardarCambiosProcesoUtilidades,"nuevoguardarcambios_button","Nue",this.procesoutilidadesSessionBean.getEsGuardarRelacionado());
FuncionesSwing.setBoldButton(this.jButtonNuevoGuardarCambiosProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
//HOT KEYS2
/*
T->Nuevo Tabla
*/
//NUEVO GUARDAR CAMBIOS O NUEVO TABLA
sMapKey = "NuevoGuardarCambiosProcesoUtilidades";
inputMap = this.jButtonNuevoGuardarCambiosProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO_TABLA") , FuncionesSwing.getMaskKey("NUEVO_TABLA")), sMapKey);
this.jButtonNuevoGuardarCambiosProcesoUtilidades.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"NuevoGuardarCambiosProcesoUtilidades"));
//RECARGAR
sMapKey = "RecargarInformacionProcesoUtilidades";
inputMap = this.jButtonRecargarInformacionProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("RECARGAR") , FuncionesSwing.getMaskKey("RECARGAR")), sMapKey);
this.jButtonRecargarInformacionProcesoUtilidades.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"RecargarInformacionProcesoUtilidades"));
//SIGUIENTES
sMapKey = "SiguientesProcesoUtilidades";
inputMap = this.jButtonSiguientesProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("SIGUIENTES") , FuncionesSwing.getMaskKey("SIGUIENTES")), sMapKey);
this.jButtonSiguientesProcesoUtilidades.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"SiguientesProcesoUtilidades"));
//ANTERIORES
sMapKey = "AnterioresProcesoUtilidades";
inputMap = this.jButtonAnterioresProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ANTERIORES") , FuncionesSwing.getMaskKey("ANTERIORES")), sMapKey);
this.jButtonAnterioresProcesoUtilidades.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"AnterioresProcesoUtilidades"));
//HOT KEYS2
//DETALLE
//TOOLBAR
//INDICES BUSQUEDA
//INDICES BUSQUEDA_FIN
//INDICES BUSQUEDA
if(!this.conCargarMinimo) {
this.inicializarElementosBusquedasProcesoUtilidades();
}
//INDICES BUSQUEDA_FIN
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
//ELEMENTOS TABLAS PARAMETOS_FIN
//ESTA EN BEAN
/*
this.jTabbedPaneRelacionesProcesoUtilidades.setMinimumSize(new Dimension(this.getWidth(),ProcesoUtilidadesBean.ALTO_TABPANE_RELACIONES + FuncionesSwing.getValorProporcion(ProcesoUtilidadesBean.ALTO_TABPANE_RELACIONES,0)));
this.jTabbedPaneRelacionesProcesoUtilidades.setMaximumSize(new Dimension(this.getWidth(),ProcesoUtilidadesBean.ALTO_TABPANE_RELACIONES + FuncionesSwing.getValorProporcion(ProcesoUtilidadesBean.ALTO_TABPANE_RELACIONES,0)));
this.jTabbedPaneRelacionesProcesoUtilidades.setPreferredSize(new Dimension(this.getWidth(),ProcesoUtilidadesBean.ALTO_TABPANE_RELACIONES + FuncionesSwing.getValorProporcion(ProcesoUtilidadesBean.ALTO_TABPANE_RELACIONES,0)));
*/
int iPosXAccionPaginacion=0;
GridBagLayout gridaBagLayoutPaginacionProcesoUtilidades = new GridBagLayout();
this.jPanelPaginacionProcesoUtilidades.setLayout(gridaBagLayoutPaginacionProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.EAST;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = 0;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionProcesoUtilidades.add(this.jButtonAnterioresProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXAccionPaginacion++;
this.gridBagConstraintsProcesoUtilidades.gridy = 0;
this.jPanelPaginacionProcesoUtilidades.add(this.jButtonNuevoGuardarCambiosProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXAccionPaginacion++;
this.gridBagConstraintsProcesoUtilidades.gridy = 0;
this.jPanelPaginacionProcesoUtilidades.add(this.jButtonSiguientesProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
iPosXAccionPaginacion=0;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = 1;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionProcesoUtilidades.add(this.jButtonNuevoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
if(!this.procesoutilidadesSessionBean.getEsGuardarRelacionado()
&& !this.conCargarMinimo) {
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = 1;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionProcesoUtilidades.add(this.jButtonGuardarCambiosTablaProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
}
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = 1;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionProcesoUtilidades.add(this.jButtonProcesarInformacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = 1;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionProcesoUtilidades.add(this.jButtonDuplicarProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = 1;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionProcesoUtilidades.add(this.jButtonCopiarProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = 1;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionProcesoUtilidades.add(this.jButtonVerFormProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = 1;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionProcesoUtilidades.add(this.jButtonCerrarProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.jButtonRecargarInformacionProcesoUtilidades.setMinimumSize(new Dimension(95,25));
this.jButtonRecargarInformacionProcesoUtilidades.setMaximumSize(new Dimension(95,25));
this.jButtonRecargarInformacionProcesoUtilidades.setPreferredSize(new Dimension(95,25));
FuncionesSwing.setBoldButton(this.jButtonRecargarInformacionProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jComboBoxTiposArchivosReportesProcesoUtilidades.setMinimumSize(new Dimension(105,20));
this.jComboBoxTiposArchivosReportesProcesoUtilidades.setMaximumSize(new Dimension(105,20));
this.jComboBoxTiposArchivosReportesProcesoUtilidades.setPreferredSize(new Dimension(105,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposArchivosReportesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposReportesProcesoUtilidades.setMinimumSize(new Dimension(100,20));
this.jComboBoxTiposReportesProcesoUtilidades.setMaximumSize(new Dimension(100,20));
this.jComboBoxTiposReportesProcesoUtilidades.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposReportesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposGraficosReportesProcesoUtilidades.setMinimumSize(new Dimension(80,20));
this.jComboBoxTiposGraficosReportesProcesoUtilidades.setMaximumSize(new Dimension(80,20));
this.jComboBoxTiposGraficosReportesProcesoUtilidades.setPreferredSize(new Dimension(80,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposGraficosReportesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposPaginacionProcesoUtilidades.setMinimumSize(new Dimension(80,20));
this.jComboBoxTiposPaginacionProcesoUtilidades.setMaximumSize(new Dimension(80,20));
this.jComboBoxTiposPaginacionProcesoUtilidades.setPreferredSize(new Dimension(80,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposPaginacionProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposRelacionesProcesoUtilidades.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposRelacionesProcesoUtilidades.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposRelacionesProcesoUtilidades.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposRelacionesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposAccionesProcesoUtilidades.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesProcesoUtilidades.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesProcesoUtilidades.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposSeleccionarProcesoUtilidades.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposSeleccionarProcesoUtilidades.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposSeleccionarProcesoUtilidades.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposSeleccionarProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jCheckBoxConAltoMaximoTablaProcesoUtilidades.setMinimumSize(new Dimension(20,20));
this.jCheckBoxConAltoMaximoTablaProcesoUtilidades.setMaximumSize(new Dimension(20,20));
this.jCheckBoxConAltoMaximoTablaProcesoUtilidades.setPreferredSize(new Dimension(20,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxConAltoMaximoTablaProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jCheckBoxConGraficoReporteProcesoUtilidades.setMinimumSize(new Dimension(60,20));
this.jCheckBoxConGraficoReporteProcesoUtilidades.setMaximumSize(new Dimension(60,20));
this.jCheckBoxConGraficoReporteProcesoUtilidades.setPreferredSize(new Dimension(60,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxConGraficoReporteProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);
this.jCheckBoxSeleccionarTodosProcesoUtilidades.setMinimumSize(new Dimension(100,20));
this.jCheckBoxSeleccionarTodosProcesoUtilidades.setMaximumSize(new Dimension(100,20));
this.jCheckBoxSeleccionarTodosProcesoUtilidades.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxSeleccionarTodosProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jCheckBoxSeleccionadosProcesoUtilidades.setMinimumSize(new Dimension(20,20));
this.jCheckBoxSeleccionadosProcesoUtilidades.setMaximumSize(new Dimension(20,20));
this.jCheckBoxSeleccionadosProcesoUtilidades.setPreferredSize(new Dimension(20,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxSeleccionadosProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
GridBagLayout gridaBagParametrosReportesProcesoUtilidades = new GridBagLayout();
GridBagLayout gridaBagParametrosReportesAccionesProcesoUtilidades = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar1ProcesoUtilidades = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar2ProcesoUtilidades = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar3ProcesoUtilidades = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar4ProcesoUtilidades = new GridBagLayout();
int iGridxParametrosReportes=0;
int iGridyParametrosReportes=0;
int iGridxParametrosAuxiliar=0;
int iGridyParametrosAuxiliar=0;
this.jPanelParametrosReportesProcesoUtilidades.setLayout(gridaBagParametrosReportesProcesoUtilidades);
this.jPanelParametrosReportesAccionesProcesoUtilidades.setLayout(gridaBagParametrosReportesAccionesProcesoUtilidades);
this.jPanelParametrosAuxiliar1ProcesoUtilidades.setLayout(gridaBagParametrosAuxiliar1ProcesoUtilidades);
this.jPanelParametrosAuxiliar2ProcesoUtilidades.setLayout(gridaBagParametrosAuxiliar2ProcesoUtilidades);
this.jPanelParametrosAuxiliar3ProcesoUtilidades.setLayout(gridaBagParametrosAuxiliar3ProcesoUtilidades);
this.jPanelParametrosAuxiliar4ProcesoUtilidades.setLayout(gridaBagParametrosAuxiliar4ProcesoUtilidades);
//this.jPanelParametrosAuxiliar5ProcesoUtilidades.setLayout(gridaBagParametrosAuxiliar2ProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesProcesoUtilidades.add(this.jButtonRecargarInformacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//PAGINACION
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar1ProcesoUtilidades.add(this.jComboBoxTiposPaginacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//CON ALTO MAXIMO TABLA
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar1ProcesoUtilidades.add(this.jCheckBoxConAltoMaximoTablaProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//TIPOS ARCHIVOS REPORTES
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar1ProcesoUtilidades.add(this.jComboBoxTiposArchivosReportesProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//USANDO AUXILIAR
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesProcesoUtilidades.add(this.jPanelParametrosAuxiliar1ProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//USANDO AUXILIAR FIN
//AUXILIAR4 TIPOS REPORTES Y TIPOS GRAFICOS REPORTES
iGridxParametrosAuxiliar=0;
iGridyParametrosAuxiliar=0;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar4ProcesoUtilidades.add(this.jComboBoxTiposReportesProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
//POR EL MOMENTO SOLO SE UTILIZA EN REPORTES DINAMICOS SIMPLES
//this.jPanelParametrosAuxiliar4ProcesoUtilidades.add(this.jComboBoxTiposGraficosReportesProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//AUXILIAR4 TIPOS REPORTES Y TIPOS GRAFICOS REPORTES
//USANDO AUXILIAR 4
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesProcesoUtilidades.add(this.jPanelParametrosAuxiliar4ProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//USANDO AUXILIAR 4 FIN
//TIPOS REPORTES
/*
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;//iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosReportes++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesProcesoUtilidades.add(this.jComboBoxTiposReportesProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
*/
//GENERAR REPORTE (jCheckBoxExportar)
/*
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesProcesoUtilidades.add(this.jCheckBoxGenerarReporteProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
*/
iGridxParametrosAuxiliar=0;
iGridyParametrosAuxiliar=0;
//USANDO AUXILIAR
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesProcesoUtilidades.add(this.jPanelParametrosAuxiliar2ProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//USANDO AUXILIAR FIN
//PARAMETROS ACCIONES
//iGridxParametrosReportes=1;
iGridxParametrosReportes=0;
iGridyParametrosReportes=1;
/*
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx =iGridxParametrosReportes++;
this.jPanelParametrosReportesProcesoUtilidades.add(this.jLabelAccionesProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
*/
//DEJA UN ESPACIO CUANDO ES MODULO, UNO A UNO FK O PROCESO
iGridxParametrosReportes++;
//PARAMETROS_ACCIONES-PARAMETROS_REPORTES
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesProcesoUtilidades.add(this.jComboBoxTiposSeleccionarProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
/*
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx =iGridxParametrosReportes++;
this.jPanelParametrosReportesProcesoUtilidades.add(this.jCheckBoxSeleccionarTodosProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx =iGridxParametrosReportes++;
this.jPanelParametrosReportesProcesoUtilidades.add(this.jCheckBoxConGraficoReporteProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
*/
iGridxParametrosAuxiliar=0;
iGridyParametrosAuxiliar=0;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar3ProcesoUtilidades.add(this.jCheckBoxSeleccionarTodosProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar3ProcesoUtilidades.add(this.jCheckBoxSeleccionadosProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar3ProcesoUtilidades.add(this.jCheckBoxConGraficoReporteProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//USANDO AUXILIAR3
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesProcesoUtilidades.add(this.jPanelParametrosAuxiliar3ProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//USANDO AUXILIAR3 FIN
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyParametrosReportes;
this.gridBagConstraintsProcesoUtilidades.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesProcesoUtilidades.add(this.jComboBoxTiposAccionesProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
;
//ELEMENTOS TABLAS PARAMETOS
//SUBPANELES POR CAMPO
if(!this.conCargarMinimo) {
//SUBPANELES EN PANEL CAMPOS
}
//ELEMENTOS TABLAS PARAMETOS_FIN
/*
GridBagLayout gridaBagLayoutDatosProcesoUtilidades = new GridBagLayout();
this.jScrollPanelDatosProcesoUtilidades.setLayout(gridaBagLayoutDatosProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = 0;
this.gridBagConstraintsProcesoUtilidades.gridx = 0;
this.jScrollPanelDatosProcesoUtilidades.add(this.jTableDatosProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
*/
this.redimensionarTablaDatos(-1);
this.jScrollPanelDatosProcesoUtilidades.setViewportView(this.jTableDatosProcesoUtilidades);
this.jTableDatosProcesoUtilidades.setFillsViewportHeight(true);
this.jTableDatosProcesoUtilidades.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
Integer iGridXParametrosAccionesFormulario=0;
Integer iGridYParametrosAccionesFormulario=0;
GridBagLayout gridaBagLayoutAccionesProcesoUtilidades= new GridBagLayout();
this.jPanelAccionesProcesoUtilidades.setLayout(gridaBagLayoutAccionesProcesoUtilidades);
/*
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = 0;
this.gridBagConstraintsProcesoUtilidades.gridx = 0;
this.jPanelAccionesProcesoUtilidades.add(this.jButtonNuevoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
*/
int iPosXAccion=0;
if(!this.conCargarMinimo) {
//BYDAN_BUSQUEDAS
GridBagLayout gridaBagLayoutBusquedaProcesoUtilidadesProcesoUtilidades= new GridBagLayout();
gridaBagLayoutBusquedaProcesoUtilidadesProcesoUtilidades.rowHeights = new int[] {1};
gridaBagLayoutBusquedaProcesoUtilidadesProcesoUtilidades.columnWidths = new int[] {1};
gridaBagLayoutBusquedaProcesoUtilidadesProcesoUtilidades.rowWeights = new double[]{0.0, 0.0, 0.0};
gridaBagLayoutBusquedaProcesoUtilidadesProcesoUtilidades.columnWeights = new double[]{0.0, 1.0};
jPanelBusquedaProcesoUtilidadesProcesoUtilidades.setLayout(gridaBagLayoutBusquedaProcesoUtilidadesProcesoUtilidades);
gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
gridBagConstraintsProcesoUtilidades.gridy = 0;
gridBagConstraintsProcesoUtilidades.gridx = 0;
jPanelBusquedaProcesoUtilidadesProcesoUtilidades.add(jLabelid_anioBusquedaProcesoUtilidadesProcesoUtilidades, gridBagConstraintsProcesoUtilidades);
gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
gridBagConstraintsProcesoUtilidades.gridy = 0;
gridBagConstraintsProcesoUtilidades.gridx = 1;
jPanelBusquedaProcesoUtilidadesProcesoUtilidades.add(jComboBoxid_anioBusquedaProcesoUtilidadesProcesoUtilidades, gridBagConstraintsProcesoUtilidades);
gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
gridBagConstraintsProcesoUtilidades.gridy = 1;
gridBagConstraintsProcesoUtilidades.gridx = 0;
jPanelBusquedaProcesoUtilidadesProcesoUtilidades.add(jLabelvalorBusquedaProcesoUtilidadesProcesoUtilidades, gridBagConstraintsProcesoUtilidades);
gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
gridBagConstraintsProcesoUtilidades.gridy = 1;
gridBagConstraintsProcesoUtilidades.gridx = 1;
jPanelBusquedaProcesoUtilidadesProcesoUtilidades.add(jTextFieldvalorBusquedaProcesoUtilidadesProcesoUtilidades, gridBagConstraintsProcesoUtilidades);
gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.WEST;
gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
gridBagConstraintsProcesoUtilidades.gridy = 2;
gridBagConstraintsProcesoUtilidades.gridx =1;
jPanelBusquedaProcesoUtilidadesProcesoUtilidades.add(jButtonBusquedaProcesoUtilidadesProcesoUtilidades, gridBagConstraintsProcesoUtilidades);
jTabbedPaneBusquedasProcesoUtilidades.addTab("1.-Por Anio Por Valor ", jPanelBusquedaProcesoUtilidadesProcesoUtilidades);
jTabbedPaneBusquedasProcesoUtilidades.setMnemonicAt(0, KeyEvent.VK_1);
}
//this.setJProgressBarToJPanel();
GridBagLayout gridaBagLayoutProcesoUtilidades = new GridBagLayout();
this.jContentPane.setLayout(gridaBagLayoutProcesoUtilidades);
if(this.parametroGeneralUsuario.getcon_botones_tool_bar() && !this.procesoutilidadesSessionBean.getEsGuardarRelacionado()) {
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyPrincipal++;
this.gridBagConstraintsProcesoUtilidades.gridx = 0;
//this.gridBagConstraintsProcesoUtilidades.fill =GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.CENTER;//.CENTER;NORTH
this.gridBagConstraintsProcesoUtilidades.ipadx = 100;
this.jContentPane.add(this.jTtoolBarProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
}
//PROCESANDO EN OTRA PANTALLA
/*
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyPrincipal++;
this.gridBagConstraintsProcesoUtilidades.gridx = 0;
//this.gridBagConstraintsProcesoUtilidades.fill =GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.CENTER;
this.gridBagConstraintsProcesoUtilidades.ipadx = 100;
this.jContentPane.add(this.jPanelProgressProcess, this.gridBagConstraintsProcesoUtilidades);
*/
int iGridxBusquedasParametros=0;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
if(!this.conCargarMinimo) {
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyPrincipal++;
this.gridBagConstraintsProcesoUtilidades.gridx = 0;
this.gridBagConstraintsProcesoUtilidades.fill =GridBagConstraints.VERTICAL;//GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.anchor = GridBagConstraints.NORTHWEST;
this.gridBagConstraintsProcesoUtilidades.ipadx = 150;
if(!this.conCargarMinimo) {
this.jContentPane.add(this.jTabbedPaneBusquedasProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
}
}
//PARAMETROS TABLAS PARAMETROS
if(!this.conCargarMinimo) {
}
//PARAMETROS TABLAS PARAMETROS_FIN
//PARAMETROS REPORTES
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyPrincipal++;
this.gridBagConstraintsProcesoUtilidades.gridx = 0;
this.jContentPane.add(this.jPanelParametrosReportesProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
/*
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyPrincipal++;
this.gridBagConstraintsProcesoUtilidades.gridx = 0;
this.jContentPane.add(this.jPanelParametrosReportesAccionesProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
*/
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy =iGridyPrincipal++;
this.gridBagConstraintsProcesoUtilidades.gridx =0;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.BOTH;
//this.gridBagConstraintsProcesoUtilidades.ipady =150;
this.jContentPane.add(this.jScrollPanelDatosProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyPrincipal++;
this.gridBagConstraintsProcesoUtilidades.gridx = 0;
this.jContentPane.add(this.jPanelPaginacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
iWidthScroll=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO_RELSCROLL)+(250*0);
iHeightScroll=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO_RELSCROLL);
if(ProcesoUtilidadesJInternalFrame.CON_DATOS_FRAME) {
this.jPanelBusquedasParametrosProcesoUtilidades= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
int iGridyRelaciones=0;
GridBagLayout gridaBagLayoutBusquedasParametrosProcesoUtilidades = new GridBagLayout();
this.jPanelBusquedasParametrosProcesoUtilidades.setLayout(gridaBagLayoutBusquedasParametrosProcesoUtilidades);
if(this.parametroGeneralUsuario.getcon_botones_tool_bar()) {
}
this.jScrollPanelDatosGeneralProcesoUtilidades= new JScrollPane(jContentPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosGeneralProcesoUtilidades.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralProcesoUtilidades.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralProcesoUtilidades.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
//if(!this.conCargarMinimo) {
//}
this.conMaximoRelaciones=true;
if(this.parametroGeneralUsuario.getcon_cargar_por_parte()) {
}
Boolean tieneColumnasOcultas=false;
if(!Constantes.ISDEVELOPING) {
} else {
if(tieneColumnasOcultas) {
}
}
} else {
//DISENO_DETALLE COMENTAR Y
//DISENO_DETALLE(Solo Descomentar Seccion Inferior)
//NOTA-DISENO_DETALLE(Si cambia lo de abajo, cambiar lo comentado, Al final no es lo mismo)
}
//DISENO_DETALLE-(Descomentar)
/*
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyPrincipal++;
this.gridBagConstraintsProcesoUtilidades.gridx = 0;
this.jContentPane.add(this.jPanelCamposProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy = iGridyPrincipal++;
this.gridBagConstraintsProcesoUtilidades.gridx = 0;
this.jContentPane.add(this.jPanelCamposOcultosProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy =iGridyPrincipal++;
this.gridBagConstraintsProcesoUtilidades.gridx =0;
this.jContentPane.add(this.jPanelAccionesProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
*/
//pack();
//OCULTAR PORQUE POSIBLEMENTE ES PROCESO
//this.jPanelPaginacionProcesoUtilidades.setVisible(false);
this.jButtonAnterioresProcesoUtilidades.setVisible(false);
this.jButtonSiguientesProcesoUtilidades.setVisible(false);
this.jButtonNuevoGuardarCambiosProcesoUtilidades.setVisible(false);
this.jButtonRecargarInformacionProcesoUtilidades.setVisible(false);
this.jScrollPanelDatosProcesoUtilidades.setVisible(false);
this.jCheckBoxSeleccionarTodosProcesoUtilidades.setVisible(false);
this.jCheckBoxSeleccionadosProcesoUtilidades.setVisible(false);
this.jCheckBoxConAltoMaximoTablaProcesoUtilidades.setVisible(false);
this.jCheckBoxConGraficoReporteProcesoUtilidades.setVisible(false);
this.jComboBoxTiposArchivosReportesProcesoUtilidades.setVisible(false);
this.jComboBoxTiposReportesProcesoUtilidades.setVisible(false);
this.jComboBoxTiposGraficosReportesProcesoUtilidades.setVisible(false);
this.jComboBoxTiposPaginacionProcesoUtilidades.setVisible(false);
this.jComboBoxTiposRelacionesProcesoUtilidades.setVisible(false);
this.jComboBoxTiposAccionesProcesoUtilidades.setVisible(false);
//this.jComboBoxTiposAccionesFormularioProcesoUtilidades.setVisible(false);
this.jComboBoxTiposSeleccionarProcesoUtilidades.setVisible(false);
this.jTextFieldValorCampoGeneralProcesoUtilidades.setVisible(false);
this.jPanelParametrosReportesProcesoUtilidades.setVisible(false);
this.jTtoolBarProcesoUtilidades.setVisible(false);
this.jMenuItemAnterioresProcesoUtilidades.setVisible(false);
this.jMenuItemSiguientesProcesoUtilidades.setVisible(false);
this.jMenuItemAbrirOrderByProcesoUtilidades.setVisible(false);
this.jMenuItemMostrarOcultarProcesoUtilidades.setVisible(false);
this.jMenuItemDetalleAbrirOrderByProcesoUtilidades.setVisible(false);
this.jButtonRecargarInformacionProcesoUtilidades.setVisible(false);
this.jTextFieldValorCampoGeneralProcesoUtilidades.setVisible(false);
this.jButtonNuevoGuardarCambiosProcesoUtilidades.setVisible(false);
this.jButtonNuevoGuardarCambiosToolBarProcesoUtilidades.setVisible(false);
this.jButtonRecargarInformacionToolBarProcesoUtilidades.setVisible(false);
this.jMenuItemNuevoGuardarCambiosProcesoUtilidades.setVisible(false);
this.jMenuItemRecargarInformacionProcesoUtilidades.setVisible(false);
return this.jScrollPanelDatosGeneralProcesoUtilidades;//jContentPane;
}
/*
public void cargarReporteDinamicoProcesoUtilidades() throws Exception {
int iWidthReporteDinamico=350;
int iHeightReporteDinamico=450;//250;400;
iHeightReporteDinamico+=180;
int iPosXReporteDinamico=0;
int iPosYReporteDinamico=0;
GridBagLayout gridaBagLayoutReporteDinamicoProcesoUtilidades = new GridBagLayout();
//PANEL
this.jPanelReporteDinamicoProcesoUtilidades = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelReporteDinamicoProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelReporteDinamicoProcesoUtilidades.setName("jPanelReporteDinamicoProcesoUtilidades");
this.jPanelReporteDinamicoProcesoUtilidades.setMinimumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
this.jPanelReporteDinamicoProcesoUtilidades.setMaximumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
this.jPanelReporteDinamicoProcesoUtilidades.setPreferredSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
this.jPanelReporteDinamicoProcesoUtilidades.setLayout(gridaBagLayoutReporteDinamicoProcesoUtilidades);
this.jInternalFrameReporteDinamicoProcesoUtilidades= new ReporteDinamicoJInternalFrame();
this.jScrollPanelReporteDinamicoProcesoUtilidades = new JScrollPane();
//PANEL_CONTROLES
//this.jScrollColumnasSelectReporteProcesoUtilidades= new JScrollPane();
//JINTERNAL FRAME
this.jInternalFrameReporteDinamicoProcesoUtilidades.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameReporteDinamicoProcesoUtilidades.setjInternalFrameParent(this);
this.jInternalFrameReporteDinamicoProcesoUtilidades.setTitle("REPORTE DINAMICO");
this.jInternalFrameReporteDinamicoProcesoUtilidades.setSize(iWidthReporteDinamico+70,iHeightReporteDinamico+100);
this.jInternalFrameReporteDinamicoProcesoUtilidades.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameReporteDinamicoProcesoUtilidades.setResizable(true);
this.jInternalFrameReporteDinamicoProcesoUtilidades.setClosable(true);
this.jInternalFrameReporteDinamicoProcesoUtilidades.setMaximizable(true);
//SCROLL PANEL
//this.jScrollPanelReporteDinamicoProcesoUtilidades.setMinimumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
//this.jScrollPanelReporteDinamicoProcesoUtilidades.setMaximumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
//this.jScrollPanelReporteDinamicoProcesoUtilidades.setPreferredSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
//this.jScrollPanelReporteDinamicoProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Proceso Utilidadeses"));
//CONTROLES-ELEMENTOS
//LABEL SELECT COLUMNAS
this.jLabelColumnasSelectReporteProcesoUtilidades = new JLabelMe();
this.jLabelColumnasSelectReporteProcesoUtilidades.setText("Columnas Seleccion");
this.jLabelColumnasSelectReporteProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnasSelectReporteProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnasSelectReporteProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico=0;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jLabelColumnasSelectReporteProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//LISTA SELECT COLUMNAS
this.jListColumnasSelectReporteProcesoUtilidades = new JList<Reporte>();
this.jListColumnasSelectReporteProcesoUtilidades.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
this.jListColumnasSelectReporteProcesoUtilidades.setToolTipText("Tipos de Seleccion");
this.jListColumnasSelectReporteProcesoUtilidades.setMinimumSize(new Dimension(145,300));
this.jListColumnasSelectReporteProcesoUtilidades.setMaximumSize(new Dimension(145,300));
this.jListColumnasSelectReporteProcesoUtilidades.setPreferredSize(new Dimension(145,300));
//SCROLL_PANEL_CONTROL
this.jScrollColumnasSelectReporteProcesoUtilidades=new JScrollPane(this.jListColumnasSelectReporteProcesoUtilidades);
this.jScrollColumnasSelectReporteProcesoUtilidades.setMinimumSize(new Dimension(180,150));
this.jScrollColumnasSelectReporteProcesoUtilidades.setMaximumSize(new Dimension(180,150));
this.jScrollColumnasSelectReporteProcesoUtilidades.setPreferredSize(new Dimension(180,150));
this.jScrollColumnasSelectReporteProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("COLUMNAS"));
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
//this.jPanelReporteDinamicoProcesoUtilidades.add(this.jListColumnasSelectReporteProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jScrollColumnasSelectReporteProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//LABEL SELECT RELACIONES
this.jLabelRelacionesSelectReporteProcesoUtilidades = new JLabelMe();
this.jLabelRelacionesSelectReporteProcesoUtilidades.setText("Relaciones Seleccion");
this.jLabelRelacionesSelectReporteProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelRelacionesSelectReporteProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelRelacionesSelectReporteProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
//LABEL SELECT RELACIONES_FIN
//LISTA SELECT RELACIONES
this.jListRelacionesSelectReporteProcesoUtilidades = new JList<Reporte>();
this.jListRelacionesSelectReporteProcesoUtilidades.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
this.jListRelacionesSelectReporteProcesoUtilidades.setToolTipText("Tipos de Seleccion");
this.jListRelacionesSelectReporteProcesoUtilidades.setMinimumSize(new Dimension(145,300));
this.jListRelacionesSelectReporteProcesoUtilidades.setMaximumSize(new Dimension(145,300));
this.jListRelacionesSelectReporteProcesoUtilidades.setPreferredSize(new Dimension(145,300));
//SCROLL_PANEL_CONTROL
this.jScrollRelacionesSelectReporteProcesoUtilidades=new JScrollPane(this.jListRelacionesSelectReporteProcesoUtilidades);
this.jScrollRelacionesSelectReporteProcesoUtilidades.setMinimumSize(new Dimension(180,120));
this.jScrollRelacionesSelectReporteProcesoUtilidades.setMaximumSize(new Dimension(180,120));
this.jScrollRelacionesSelectReporteProcesoUtilidades.setPreferredSize(new Dimension(180,120));
this.jScrollRelacionesSelectReporteProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("RELACIONES"));
this.jCheckBoxConGraficoDinamicoProcesoUtilidades = new JCheckBoxMe();
this.jComboBoxColumnaCategoriaGraficoProcesoUtilidades = new JComboBoxMe();
this.jListColumnasValoresGraficoProcesoUtilidades = new JList<Reporte>();
//COMBO TIPOS REPORTES
this.jComboBoxTiposReportesDinamicoProcesoUtilidades = new JComboBoxMe();
this.jComboBoxTiposReportesDinamicoProcesoUtilidades.setToolTipText("Tipos De Reporte");
this.jComboBoxTiposReportesDinamicoProcesoUtilidades.setMinimumSize(new Dimension(100,20));
this.jComboBoxTiposReportesDinamicoProcesoUtilidades.setMaximumSize(new Dimension(100,20));
this.jComboBoxTiposReportesDinamicoProcesoUtilidades.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposReportesDinamicoProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
//COMBO TIPOS REPORTES
//COMBO TIPOS ARCHIVOS
this.jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades = new JComboBoxMe();
this.jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades.setToolTipText("Tipos Archivos");
this.jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades.setMinimumSize(new Dimension(100,20));
this.jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades.setMaximumSize(new Dimension(100,20));
this.jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
//COMBO TIPOS ARCHIVOS
//LABEL CON GRAFICO DINAMICO
this.jLabelConGraficoDinamicoProcesoUtilidades = new JLabelMe();
this.jLabelConGraficoDinamicoProcesoUtilidades.setText("Con Grafico");
this.jLabelConGraficoDinamicoProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelConGraficoDinamicoProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelConGraficoDinamicoProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jLabelConGraficoDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//CHECKBOX CON GRAFICO DINAMICO
this.jCheckBoxConGraficoDinamicoProcesoUtilidades = new JCheckBoxMe();
this.jCheckBoxConGraficoDinamicoProcesoUtilidades.setText("Graf.");
this.jCheckBoxConGraficoDinamicoProcesoUtilidades.setToolTipText("Con Grafico");
this.jCheckBoxConGraficoDinamicoProcesoUtilidades.setMinimumSize(new Dimension(100,20));
this.jCheckBoxConGraficoDinamicoProcesoUtilidades.setMaximumSize(new Dimension(100,20));
this.jCheckBoxConGraficoDinamicoProcesoUtilidades.setPreferredSize(new Dimension(100,20));
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jCheckBoxConGraficoDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//LABEL COMBO COLUMNA CATEGORIA
this.jLabelColumnaCategoriaGraficoProcesoUtilidades = new JLabelMe();
this.jLabelColumnaCategoriaGraficoProcesoUtilidades.setText("Categoria Grafico");
this.jLabelColumnaCategoriaGraficoProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnaCategoriaGraficoProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnaCategoriaGraficoProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jLabelColumnaCategoriaGraficoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//COMBO COLUMNA CATEGORIA
this.jComboBoxColumnaCategoriaGraficoProcesoUtilidades = new JComboBoxMe();
//this.jComboBoxColumnaCategoriaGraficoProcesoUtilidades.setText("Accion");
this.jComboBoxColumnaCategoriaGraficoProcesoUtilidades.setToolTipText("Tipos de Seleccion");
this.jComboBoxColumnaCategoriaGraficoProcesoUtilidades.setMinimumSize(new Dimension(145,20));
this.jComboBoxColumnaCategoriaGraficoProcesoUtilidades.setMaximumSize(new Dimension(145,20));
this.jComboBoxColumnaCategoriaGraficoProcesoUtilidades.setPreferredSize(new Dimension(145,20));
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jComboBoxColumnaCategoriaGraficoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//LABEL COMBO COLUMNA CATEGORIA VALOR
this.jLabelColumnaCategoriaValorProcesoUtilidades = new JLabelMe();
this.jLabelColumnaCategoriaValorProcesoUtilidades.setText("Categoria Valor");
this.jLabelColumnaCategoriaValorProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnaCategoriaValorProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnaCategoriaValorProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jLabelColumnaCategoriaValorProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//COMBO COLUMNA CATEGORIA VALOR
this.jComboBoxColumnaCategoriaValorProcesoUtilidades = new JComboBoxMe();
//this.jComboBoxColumnaCategoriaValorProcesoUtilidades.setText("Accion");
this.jComboBoxColumnaCategoriaValorProcesoUtilidades.setToolTipText("Tipos de Seleccion");
this.jComboBoxColumnaCategoriaValorProcesoUtilidades.setMinimumSize(new Dimension(145,20));
this.jComboBoxColumnaCategoriaValorProcesoUtilidades.setMaximumSize(new Dimension(145,20));
this.jComboBoxColumnaCategoriaValorProcesoUtilidades.setPreferredSize(new Dimension(145,20));
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jComboBoxColumnaCategoriaValorProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//LABEL VALORES GRAFICO COLUMNAS
this.jLabelColumnasValoresGraficoProcesoUtilidades = new JLabelMe();
this.jLabelColumnasValoresGraficoProcesoUtilidades.setText("Columnas Valor Graf.");
this.jLabelColumnasValoresGraficoProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnasValoresGraficoProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnasValoresGraficoProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jLabelColumnasValoresGraficoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//LISTA VALORES GRAFICO COLUMNAS
this.jListColumnasValoresGraficoProcesoUtilidades = new JList<Reporte>();
this.jListColumnasValoresGraficoProcesoUtilidades.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
this.jListColumnasValoresGraficoProcesoUtilidades.setToolTipText("VALORES GRAFICO");
this.jListColumnasValoresGraficoProcesoUtilidades.setMinimumSize(new Dimension(145,300));
this.jListColumnasValoresGraficoProcesoUtilidades.setMaximumSize(new Dimension(145,300));
this.jListColumnasValoresGraficoProcesoUtilidades.setPreferredSize(new Dimension(145,300));
//SCROLL_VALORES GRAFICO COLUMNAS
this.jScrollColumnasValoresGraficoProcesoUtilidades=new JScrollPane(this.jListColumnasValoresGraficoProcesoUtilidades);
this.jScrollColumnasValoresGraficoProcesoUtilidades.setMinimumSize(new Dimension(180,150));
this.jScrollColumnasValoresGraficoProcesoUtilidades.setMaximumSize(new Dimension(180,150));
this.jScrollColumnasValoresGraficoProcesoUtilidades.setPreferredSize(new Dimension(180,150));
this.jScrollColumnasValoresGraficoProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("COLUMNAS"));
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
//this.jPanelReporteDinamicoProcesoUtilidades.add(this.jListColumnasSelectReporteProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jScrollColumnasValoresGraficoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//LABEL TIPOS GRAFICO REPORTES
this.jLabelTiposGraficosReportesDinamicoProcesoUtilidades = new JLabelMe();
this.jLabelTiposGraficosReportesDinamicoProcesoUtilidades.setText("Tipo Grafico");
this.jLabelTiposGraficosReportesDinamicoProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelTiposGraficosReportesDinamicoProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelTiposGraficosReportesDinamicoProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jLabelTiposGraficosReportesDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//COMBO TIPO GRAFICO REPORTE
this.jComboBoxTiposGraficosReportesDinamicoProcesoUtilidades = new JComboBoxMe();
//this.jComboBoxColumnaCategoriaGraficoProcesoUtilidades.setText("Accion");
this.jComboBoxTiposGraficosReportesDinamicoProcesoUtilidades.setToolTipText("Tipos de Seleccion");
this.jComboBoxTiposGraficosReportesDinamicoProcesoUtilidades.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposGraficosReportesDinamicoProcesoUtilidades.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposGraficosReportesDinamicoProcesoUtilidades.setPreferredSize(new Dimension(145,20));
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jComboBoxTiposGraficosReportesDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//LABEL GENERAR EXCEL
this.jLabelGenerarExcelReporteDinamicoProcesoUtilidades = new JLabelMe();
this.jLabelGenerarExcelReporteDinamicoProcesoUtilidades.setText("Tipos de Reporte");
this.jLabelGenerarExcelReporteDinamicoProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelGenerarExcelReporteDinamicoProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelGenerarExcelReporteDinamicoProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jLabelGenerarExcelReporteDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//BOTON GENERAR EXCEL
this.jButtonGenerarExcelReporteDinamicoProcesoUtilidades = new JButtonMe();
this.jButtonGenerarExcelReporteDinamicoProcesoUtilidades.setText("Generar Excel");
FuncionesSwing.addImagenButtonGeneral(this.jButtonGenerarExcelReporteDinamicoProcesoUtilidades,"generar_excel_reporte_dinamico_button","Generar EXCEL");
this.jButtonGenerarExcelReporteDinamicoProcesoUtilidades.setToolTipText("Generar EXCEL"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO);
//this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
//this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
//this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
//this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
//this.jPanelReporteDinamicoProcesoUtilidades.add(this.jButtonGenerarExcelReporteDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//COMBO TIPOS REPORTES
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jComboBoxTiposReportesDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//LABEL TIPOS DE ARCHIVO
this.jLabelTiposArchivoReporteDinamicoProcesoUtilidades = new JLabelMe();
this.jLabelTiposArchivoReporteDinamicoProcesoUtilidades.setText("Tipos de Archivo");
this.jLabelTiposArchivoReporteDinamicoProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelTiposArchivoReporteDinamicoProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelTiposArchivoReporteDinamicoProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jLabelTiposArchivoReporteDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//COMBO TIPOS ARCHIVOS
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jComboBoxTiposArchivosReportesDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//BOTON GENERAR
this.jButtonGenerarReporteDinamicoProcesoUtilidades = new JButtonMe();
this.jButtonGenerarReporteDinamicoProcesoUtilidades.setText("Generar");
FuncionesSwing.addImagenButtonGeneral(this.jButtonGenerarReporteDinamicoProcesoUtilidades,"generar_reporte_dinamico_button","Generar");
this.jButtonGenerarReporteDinamicoProcesoUtilidades.setToolTipText("Generar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO);
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jButtonGenerarReporteDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//BOTON CERRAR
this.jButtonCerrarReporteDinamicoProcesoUtilidades = new JButtonMe();
this.jButtonCerrarReporteDinamicoProcesoUtilidades.setText("Cancelar");
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarReporteDinamicoProcesoUtilidades,"cerrar_reporte_dinamico_button","Cancelar");
this.jButtonCerrarReporteDinamicoProcesoUtilidades.setToolTipText("Cancelar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoProcesoUtilidades.add(this.jButtonCerrarReporteDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//GLOBAL AGREGAR PANELES
GridBagLayout gridaBagLayoutReporteDinamicoPrincipalProcesoUtilidades = new GridBagLayout();
this.jScrollPanelReporteDinamicoProcesoUtilidades= new JScrollPane(jPanelReporteDinamicoProcesoUtilidades,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelReporteDinamicoProcesoUtilidades.setMinimumSize(new Dimension(iWidthReporteDinamico+90,iHeightReporteDinamico+90));
this.jScrollPanelReporteDinamicoProcesoUtilidades.setMaximumSize(new Dimension(iWidthReporteDinamico+90,iHeightReporteDinamico+90));
this.jScrollPanelReporteDinamicoProcesoUtilidades.setPreferredSize(new Dimension(iWidthReporteDinamico+90,iHeightReporteDinamico+90));
this.jScrollPanelReporteDinamicoProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Proceso Utilidadeses"));
iPosXReporteDinamico=0;
iPosYReporteDinamico=0;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy =iPosYReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.gridx =iPosXReporteDinamico;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.BOTH;
this.jInternalFrameReporteDinamicoProcesoUtilidades.setContentPane(new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true));
this.jInternalFrameReporteDinamicoProcesoUtilidades.getContentPane().setLayout(gridaBagLayoutReporteDinamicoPrincipalProcesoUtilidades);
this.jInternalFrameReporteDinamicoProcesoUtilidades.getContentPane().add(this.jScrollPanelReporteDinamicoProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
}
*/
/*
public void cargarImportacionProcesoUtilidades() throws Exception {
int iWidthImportacion=350;
int iHeightImportacion=250;//400;
int iPosXImportacion=0;
int iPosYImportacion=0;
GridBagLayout gridaBagLayoutImportacionProcesoUtilidades = new GridBagLayout();
//PANEL
this.jPanelImportacionProcesoUtilidades = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelImportacionProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelImportacionProcesoUtilidades.setName("jPanelImportacionProcesoUtilidades");
this.jPanelImportacionProcesoUtilidades.setMinimumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jPanelImportacionProcesoUtilidades.setMaximumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jPanelImportacionProcesoUtilidades.setPreferredSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jPanelImportacionProcesoUtilidades.setLayout(gridaBagLayoutImportacionProcesoUtilidades);
this.jInternalFrameImportacionProcesoUtilidades= new ImportacionJInternalFrame();
//this.jInternalFrameImportacionProcesoUtilidades= new ImportacionJInternalFrame();
this.jScrollPanelImportacionProcesoUtilidades = new JScrollPane();
//PANEL_CONTROLES
//this.jScrollColumnasSelectReporteProcesoUtilidades= new JScrollPane();
//JINTERNAL FRAME
this.jInternalFrameImportacionProcesoUtilidades.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameImportacionProcesoUtilidades.setjInternalFrameParent(this);
this.jInternalFrameImportacionProcesoUtilidades.setTitle("REPORTE DINAMICO");
this.jInternalFrameImportacionProcesoUtilidades.setSize(iWidthImportacion+70,iHeightImportacion+100);
this.jInternalFrameImportacionProcesoUtilidades.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameImportacionProcesoUtilidades.setResizable(true);
this.jInternalFrameImportacionProcesoUtilidades.setClosable(true);
this.jInternalFrameImportacionProcesoUtilidades.setMaximizable(true);
//JINTERNAL FRAME IMPORTACION
this.jInternalFrameImportacionProcesoUtilidades.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameImportacionProcesoUtilidades.setjInternalFrameParent(this);
this.jInternalFrameImportacionProcesoUtilidades.setTitle("IMPORTACION");
this.jInternalFrameImportacionProcesoUtilidades.setSize(iWidthImportacion+70,iHeightImportacion+100);
this.jInternalFrameImportacionProcesoUtilidades.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameImportacionProcesoUtilidades.setResizable(true);
this.jInternalFrameImportacionProcesoUtilidades.setClosable(true);
this.jInternalFrameImportacionProcesoUtilidades.setMaximizable(true);
//SCROLL PANEL
this.jScrollPanelImportacionProcesoUtilidades.setMinimumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jScrollPanelImportacionProcesoUtilidades.setMaximumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jScrollPanelImportacionProcesoUtilidades.setPreferredSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jScrollPanelImportacionProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Proceso Utilidadeses"));
//LABEL ARCHIVO IMPORTACION
this.jLabelArchivoImportacionProcesoUtilidades = new JLabelMe();
this.jLabelArchivoImportacionProcesoUtilidades.setText("ARCHIVO IMPORTACION");
this.jLabelArchivoImportacionProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelArchivoImportacionProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelArchivoImportacionProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXImportacion=0;
iPosYImportacion++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYImportacion;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXImportacion++;
this.jPanelImportacionProcesoUtilidades.add(this.jLabelArchivoImportacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//BOTON ABRIR IMPORTACION
this.jFileChooserImportacionProcesoUtilidades = new JFileChooser();
this.jFileChooserImportacionProcesoUtilidades.setToolTipText("ESCOGER ARCHIVO"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO);
this.jButtonAbrirImportacionProcesoUtilidades = new JButtonMe();
this.jButtonAbrirImportacionProcesoUtilidades.setText("ESCOGER");
FuncionesSwing.addImagenButtonGeneral(this.jButtonAbrirImportacionProcesoUtilidades,"generar_importacion_button","ESCOGER");
this.jButtonAbrirImportacionProcesoUtilidades.setToolTipText("Generar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYImportacion;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXImportacion++;
this.jPanelImportacionProcesoUtilidades.add(this.jButtonAbrirImportacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//LABEL PATH IMPORTACION
this.jLabelPathArchivoImportacionProcesoUtilidades = new JLabelMe();
this.jLabelPathArchivoImportacionProcesoUtilidades.setText("PATH ARCHIVO");
this.jLabelPathArchivoImportacionProcesoUtilidades.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelPathArchivoImportacionProcesoUtilidades.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelPathArchivoImportacionProcesoUtilidades.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXImportacion=0;
iPosYImportacion++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYImportacion;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXImportacion++;
this.jPanelImportacionProcesoUtilidades.add(this.jLabelPathArchivoImportacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//PATH IMPORTACION
this.jTextFieldPathArchivoImportacionProcesoUtilidades=new JTextFieldMe();
this.jTextFieldPathArchivoImportacionProcesoUtilidades.setMinimumSize(new Dimension(150,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldPathArchivoImportacionProcesoUtilidades.setMaximumSize(new Dimension(150,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldPathArchivoImportacionProcesoUtilidades.setPreferredSize(new Dimension(150,Constantes.ISWING_ALTO_CONTROL));
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYImportacion;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXImportacion++;
this.jPanelImportacionProcesoUtilidades.add(this.jTextFieldPathArchivoImportacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//BOTON IMPORTACION
this.jButtonGenerarImportacionProcesoUtilidades = new JButtonMe();
this.jButtonGenerarImportacionProcesoUtilidades.setText("IMPORTAR");
FuncionesSwing.addImagenButtonGeneral(this.jButtonGenerarImportacionProcesoUtilidades,"generar_importacion_button","IMPORTAR");
this.jButtonGenerarImportacionProcesoUtilidades.setToolTipText("Generar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO);
iPosXImportacion=0;
iPosYImportacion++;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYImportacion;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXImportacion++;
this.jPanelImportacionProcesoUtilidades.add(this.jButtonGenerarImportacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//BOTON CERRAR
this.jButtonCerrarImportacionProcesoUtilidades = new JButtonMe();
this.jButtonCerrarImportacionProcesoUtilidades.setText("Cancelar");
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarImportacionProcesoUtilidades,"cerrar_reporte_dinamico_button","Cancelar");
this.jButtonCerrarImportacionProcesoUtilidades.setToolTipText("Cancelar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO);
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYImportacion;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXImportacion++;
this.jPanelImportacionProcesoUtilidades.add(this.jButtonCerrarImportacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//GLOBAL AGREGAR PANELES
GridBagLayout gridaBagLayoutImportacionPrincipalProcesoUtilidades = new GridBagLayout();
this.jScrollPanelImportacionProcesoUtilidades= new JScrollPane(jPanelImportacionProcesoUtilidades,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
iPosXImportacion=0;
iPosYImportacion=0;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy =iPosYImportacion;
this.gridBagConstraintsProcesoUtilidades.gridx =iPosXImportacion;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.BOTH;
this.jInternalFrameImportacionProcesoUtilidades.setContentPane(new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true));
this.jInternalFrameImportacionProcesoUtilidades.getContentPane().setLayout(gridaBagLayoutImportacionPrincipalProcesoUtilidades);
this.jInternalFrameImportacionProcesoUtilidades.getContentPane().add(this.jScrollPanelImportacionProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
}
*/
/*
public void cargarOrderByProcesoUtilidades(Boolean cargaMinima) throws Exception {
String sMapKey = "";
InputMap inputMap =null;
int iWidthOrderBy=350;
int iHeightOrderBy=300;//400;
int iPosXOrderBy=0;
int iPosYOrderBy=0;
if(!cargaMinima) {
this.jButtonAbrirOrderByProcesoUtilidades = new JButtonMe();
this.jButtonAbrirOrderByProcesoUtilidades.setText("Orden");
this.jButtonAbrirOrderByProcesoUtilidades.setToolTipText("Orden"+FuncionesSwing.getKeyMensaje("ORDEN"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonAbrirOrderByProcesoUtilidades,"orden_button","Orden");
FuncionesSwing.setBoldButton(this.jButtonAbrirOrderByProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
sMapKey = "AbrirOrderByProcesoUtilidades";
inputMap = this.jButtonAbrirOrderByProcesoUtilidades.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ORDEN") , FuncionesSwing.getMaskKey("ORDEN")), sMapKey);
this.jButtonAbrirOrderByProcesoUtilidades.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"AbrirOrderByProcesoUtilidades"));
GridBagLayout gridaBagLayoutOrderByProcesoUtilidades = new GridBagLayout();
//PANEL
this.jPanelOrderByProcesoUtilidades = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelOrderByProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelOrderByProcesoUtilidades.setName("jPanelOrderByProcesoUtilidades");
this.jPanelOrderByProcesoUtilidades.setMinimumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jPanelOrderByProcesoUtilidades.setMaximumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jPanelOrderByProcesoUtilidades.setPreferredSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
FuncionesSwing.setBoldPanel(this.jPanelOrderByProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jPanelOrderByProcesoUtilidades.setLayout(gridaBagLayoutOrderByProcesoUtilidades);
this.jTableDatosProcesoUtilidadesOrderBy = new JTableMe();
this.jTableDatosProcesoUtilidadesOrderBy.setAutoCreateRowSorter(true);
FuncionesSwing.setBoldTable(jTableDatosProcesoUtilidadesOrderBy,STIPO_TAMANIO_GENERAL,false,true,this);
this.jScrollPanelDatosProcesoUtilidadesOrderBy = new JScrollPane();
this.jScrollPanelDatosProcesoUtilidadesOrderBy.setBorder(javax.swing.BorderFactory.createTitledBorder("Orden"));
this.jScrollPanelDatosProcesoUtilidadesOrderBy.setViewportView(this.jTableDatosProcesoUtilidadesOrderBy);
this.jTableDatosProcesoUtilidadesOrderBy.setFillsViewportHeight(true);
this.jTableDatosProcesoUtilidadesOrderBy.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
this.jInternalFrameOrderByProcesoUtilidades= new OrderByJInternalFrame();
this.jInternalFrameOrderByProcesoUtilidades= new OrderByJInternalFrame();
this.jScrollPanelOrderByProcesoUtilidades = new JScrollPane();
//PANEL_CONTROLES
//this.jScrollColumnasSelectReporteProcesoUtilidades= new JScrollPane();
//JINTERNAL FRAME OrderBy
this.jInternalFrameOrderByProcesoUtilidades.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameOrderByProcesoUtilidades.setjInternalFrameParent(this);
this.jInternalFrameOrderByProcesoUtilidades.setTitle("Orden");
this.jInternalFrameOrderByProcesoUtilidades.setSize(iWidthOrderBy+70,iHeightOrderBy+100);
this.jInternalFrameOrderByProcesoUtilidades.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameOrderByProcesoUtilidades.setResizable(true);
this.jInternalFrameOrderByProcesoUtilidades.setClosable(true);
this.jInternalFrameOrderByProcesoUtilidades.setMaximizable(true);
//FuncionesSwing.setBoldPanel(this.jInternalFrameOrderByProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
//SCROLL PANEL
this.jScrollPanelOrderByProcesoUtilidades.setMinimumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jScrollPanelOrderByProcesoUtilidades.setMaximumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jScrollPanelOrderByProcesoUtilidades.setPreferredSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelOrderByProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jScrollPanelOrderByProcesoUtilidades.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Proceso Utilidadeses"));
//DATOS TOTALES
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy =iPosYOrderBy++;
this.gridBagConstraintsProcesoUtilidades.gridx =iPosXOrderBy;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.BOTH;
//this.gridBagConstraintsProcesoUtilidades.ipady =150;
this.jPanelOrderByProcesoUtilidades.add(jScrollPanelDatosProcesoUtilidadesOrderBy, this.gridBagConstraintsProcesoUtilidades);//this.jTableDatosProcesoUtilidadesTotales
//BOTON CERRAR
this.jButtonCerrarOrderByProcesoUtilidades = new JButtonMe();
this.jButtonCerrarOrderByProcesoUtilidades.setText("Salir");
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarOrderByProcesoUtilidades,"cerrar","Salir");//cerrar_reporte_dinamico_button
this.jButtonCerrarOrderByProcesoUtilidades.setToolTipText("Cancelar"+" "+ProcesoUtilidadesConstantesFunciones.SCLASSWEBTITULO);
FuncionesSwing.setBoldButton(this.jButtonCerrarOrderByProcesoUtilidades, STIPO_TAMANIO_GENERAL,false,true,this);;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsProcesoUtilidades.gridy = iPosYOrderBy++;
this.gridBagConstraintsProcesoUtilidades.gridx = iPosXOrderBy;
this.jPanelOrderByProcesoUtilidades.add(this.jButtonCerrarOrderByProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
//GLOBAL AGREGAR PANELES
GridBagLayout gridaBagLayoutOrderByPrincipalProcesoUtilidades = new GridBagLayout();
this.jScrollPanelOrderByProcesoUtilidades= new JScrollPane(jPanelOrderByProcesoUtilidades,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
iPosXOrderBy=0;
iPosYOrderBy=0;
this.gridBagConstraintsProcesoUtilidades = new GridBagConstraints();
this.gridBagConstraintsProcesoUtilidades.gridy =iPosYOrderBy;
this.gridBagConstraintsProcesoUtilidades.gridx =iPosXOrderBy;
this.gridBagConstraintsProcesoUtilidades.fill = GridBagConstraints.BOTH;
this.jInternalFrameOrderByProcesoUtilidades.setContentPane(new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true));
this.jInternalFrameOrderByProcesoUtilidades.getContentPane().setLayout(gridaBagLayoutOrderByPrincipalProcesoUtilidades);
this.jInternalFrameOrderByProcesoUtilidades.getContentPane().add(this.jScrollPanelOrderByProcesoUtilidades, this.gridBagConstraintsProcesoUtilidades);
} else {
this.jButtonAbrirOrderByProcesoUtilidades = new JButtonMe();
}
}
*/
public void redimensionarTablaDatos(int iNumFilas) {
this.redimensionarTablaDatos(iNumFilas,0);
}
public void redimensionarTablaDatos(int iNumFilas,int iTamanioFilaTabla) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int iWidthTable=screenSize.width*2;//screenSize.width - (screenSize.width/8);
int iWidthTableScroll=screenSize.width - (screenSize.width/8);
int iWidthTableCalculado=0;//730
int iHeightTable=0;//screenSize.height/3;
int iHeightTableTotal=0;
//ANCHO COLUMNAS SIMPLES
iWidthTableCalculado+=430;
//ANCHO COLUMNAS OCULTAS
if(Constantes.ISDEVELOPING) {
iWidthTableCalculado+=300;
}
//ANCHO COLUMNAS RELACIONES
iWidthTableCalculado+=0;
//ESPACION PARA SELECT RELACIONES
//if(this.conMaximoRelaciones
// && this.procesoutilidadesSessionBean.getConGuardarRelaciones()
// ) {
//}
//SI CALCULADO ES MENOR QUE MAXIMO
/*
if(iWidthTableCalculado<=iWidthTable) {
iWidthTable=iWidthTableCalculado;
}
*/
//SI TABLA ES MENOR QUE SCROLL
if(iWidthTableCalculado<=iWidthTableScroll) {
iWidthTableScroll=iWidthTableCalculado;
}
//NO VALE SIEMPRE PONE TAMANIO COLUMNA 200
/*
int iTotalWidth=0;
int iWidthColumn=0;
int iCountColumns=this.jTableDatosProcesoUtilidades.getColumnModel().getColumnCount();
if(iCountColumns>0) {
for(int i = 0; i < this.jTableDatosProcesoUtilidades.getColumnModel().getColumnCount(); i++) {
TableColumn column = this.jTableDatosProcesoUtilidades.getColumnModel().getColumn(i);
iWidthColumn=column.getWidth();
iTotalWidth+=iWidthColumn;
}
//iWidthTableCalculado=iTotalWidth;
}
*/
if(iTamanioFilaTabla<=0) {
//iTamanioFilaTabla=this.jTableDatosProcesoUtilidades.getRowHeight();//ProcesoUtilidadesConstantesFunciones.ITAMANIOFILATABLA;
}
if(iNumFilas>0) {
iHeightTable=(iNumFilas * iTamanioFilaTabla);
} else {
iHeightTable=iTamanioFilaTabla;
}
iHeightTableTotal=iHeightTable;
if(!this.procesoutilidadesSessionBean.getEsGuardarRelacionado()) {
if(iHeightTable > ProcesoUtilidadesConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOS) { //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS) {
//SI SE SELECCIONA MAXIMO TABLA SE AMPLIA A ALTO MAXIMO DE SCROLL, PARA QUE SCROLL NO SEA TAN PEQUE?O
if(!this.jCheckBoxConAltoMaximoTablaProcesoUtilidades.isSelected()) {
iHeightTable=ProcesoUtilidadesConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOS; //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS;
} else {
iHeightTable=iHeightTableTotal + FuncionesSwing.getValorProporcion(iHeightTableTotal,30);
}
} else {
if(iHeightTable < ProcesoUtilidadesConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOS) {//Constantes.ISWING_TAMANIOMINIMO_TABLADATOS) {
iHeightTable=ProcesoUtilidadesConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOS; //Constantes.ISWING_TAMANIOMINIMO_TABLADATOS;
}
}
} else {
if(iHeightTable > ProcesoUtilidadesConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOSREL) { //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS) {
//SI SE SELECCIONA MAXIMO TABLA SE AMPLIA A ALTO MAXIMO DE SCROLL, PARA QUE SCROLL NO SEA TAN PEQUE?O
if(!this.jCheckBoxConAltoMaximoTablaProcesoUtilidades.isSelected()) {
iHeightTable=ProcesoUtilidadesConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOSREL; //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS;
} else {
iHeightTable=iHeightTableTotal + FuncionesSwing.getValorProporcion(iHeightTableTotal,30);
}
} else {
if(iHeightTable < ProcesoUtilidadesConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOSREL) {//Constantes.ISWING_TAMANIOMINIMO_TABLADATOS) {
iHeightTable=ProcesoUtilidadesConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOSREL; //Constantes.ISWING_TAMANIOMINIMO_TABLADATOS;
}
}
}
//OJO:SE DESHABILITA CALCULADO
//NO SE UTILIZA CALCULADO SI POR DEFINICION
if(iWidthTableDefinicion>0) {
iWidthTableCalculado=iWidthTableDefinicion;
}
this.jTableDatosProcesoUtilidades.setMinimumSize(new Dimension(iWidthTableCalculado,iHeightTableTotal));
this.jTableDatosProcesoUtilidades.setMaximumSize(new Dimension(iWidthTableCalculado,iHeightTableTotal));
this.jTableDatosProcesoUtilidades.setPreferredSize(new Dimension(iWidthTableCalculado,iHeightTableTotal));//iWidthTable
this.jScrollPanelDatosProcesoUtilidades.setMinimumSize(new Dimension(iWidthTableScroll,iHeightTable));
this.jScrollPanelDatosProcesoUtilidades.setMaximumSize(new Dimension(iWidthTableScroll,iHeightTable));
this.jScrollPanelDatosProcesoUtilidades.setPreferredSize(new Dimension(iWidthTableScroll,iHeightTable));
//ORDER BY
//OrderBy
int iHeightTableOrderBy=0;
int iNumFilasOrderBy=this.arrOrderBy.size();
int iTamanioFilaTablaOrderBy=0;
if(this.jInternalFrameOrderByProcesoUtilidades!=null && this.jInternalFrameOrderByProcesoUtilidades.getjTableDatosOrderBy()!=null) {
//if(!this.procesoutilidadesSessionBean.getEsGuardarRelacionado()) {
iTamanioFilaTablaOrderBy=this.jInternalFrameOrderByProcesoUtilidades.getjTableDatosOrderBy().getRowHeight();
if(iNumFilasOrderBy>0) {
iHeightTableOrderBy=iNumFilasOrderBy * iTamanioFilaTablaOrderBy;
} else {
iHeightTableOrderBy=iTamanioFilaTablaOrderBy;
}
this.jInternalFrameOrderByProcesoUtilidades.getjTableDatosOrderBy().setMinimumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY,iHeightTableOrderBy));//iWidthTableCalculado/4
this.jInternalFrameOrderByProcesoUtilidades.getjTableDatosOrderBy().setMaximumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY,iHeightTableOrderBy));
this.jInternalFrameOrderByProcesoUtilidades.getjTableDatosOrderBy().setPreferredSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY,iHeightTableOrderBy));//iWidthTable
this.jInternalFrameOrderByProcesoUtilidades.getjScrollPanelDatosOrderBy().setMinimumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY+30,Constantes2.ISWING_TAMANIO_ALTO_TABLADATOS_ORDERBY));//iHeightTableOrderBy,iWidthTableScroll
this.jInternalFrameOrderByProcesoUtilidades.getjScrollPanelDatosOrderBy().setMaximumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY+30,Constantes2.ISWING_TAMANIO_ALTO_TABLADATOS_ORDERBY));
this.jInternalFrameOrderByProcesoUtilidades.getjScrollPanelDatosOrderBy().setPreferredSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY+30,Constantes2.ISWING_TAMANIO_ALTO_TABLADATOS_ORDERBY));
}
//ORDER BY
//this.jScrollPanelDatosProcesoUtilidades.setMinimumSize(new Dimension(iWidthTableScroll,iHeightTable));
//this.jScrollPanelDatosProcesoUtilidades.setMaximumSize(new Dimension(iWidthTableScroll,iHeightTable));
//this.jScrollPanelDatosProcesoUtilidades.setPreferredSize(new Dimension(iWidthTableScroll,iHeightTable));
//VERSION 0
/*
//SI CALCULADO ES MENOR QUE MAXIMO
if(iWidthTableCalculado<=iWidthTable) {
iWidthTable=iWidthTableCalculado;
}
//SI TABLA ES MENOR QUE SCROLL
if(iWidthTable<=iWidthTableScroll) {
iWidthTableScroll=iWidthTable;
}
*/
}
public void redimensionarTablaDatosConTamanio(int iTamanioFilaTabla) throws Exception {
int iSizeTabla=0;
//ARCHITECTURE
if(Constantes.ISUSAEJBLOGICLAYER) {
//iSizeTabla=procesoutilidadesLogic.getProcesoUtilidadess().size();
} else if(Constantes.ISUSAEJBREMOTE || Constantes.ISUSAEJBHOME) {
iSizeTabla=procesoutilidadess.size();
}
//ARCHITECTURE
this.redimensionarTablaDatos(iSizeTabla,iTamanioFilaTabla);
}
//PARA REPORTES
public static List<ProcesoUtilidades> TraerProcesoUtilidadesBeans(List<ProcesoUtilidades> procesoutilidadess,ArrayList<Classe> classes)throws Exception {
try {
for(ProcesoUtilidades procesoutilidades:procesoutilidadess) {
if(!(ProcesoUtilidadesConstantesFunciones.S_TIPOREPORTE_EXTRA.equals(Constantes2.S_REPORTE_EXTRA_GROUP_GENERICO)
|| ProcesoUtilidadesConstantesFunciones.S_TIPOREPORTE_EXTRA.equals(Constantes2.S_REPORTE_EXTRA_GROUP_TOTALES_GENERICO))
) {
procesoutilidades.setsDetalleGeneralEntityReporte(ProcesoUtilidadesConstantesFunciones.getProcesoUtilidadesDescripcion(procesoutilidades));
} else {
//procesoutilidades.setsDetalleGeneralEntityReporte(procesoutilidades.getsDetalleGeneralEntityReporte());
}
//procesoutilidadesbeans.add(procesoutilidadesbean);
}
} catch(Exception ex) {
throw ex;
}
return procesoutilidadess;
}
//PARA REPORTES FIN
}
| 50.303107 | 375 | 0.818024 |
76b0b23493f67ce1201e4dfad47b8aa7f7ef23a4 | 9,062 | package cn.huan.mall.product.service.impl;
import cn.huan.common.constant.ProductConstant;
import cn.huan.common.utils.PageUtils;
import cn.huan.common.utils.Query;
import cn.huan.mall.product.dao.AttrDao;
import cn.huan.mall.product.dao.AttrGroupDao;
import cn.huan.mall.product.dao.CategoryDao;
import cn.huan.mall.product.entity.AttrAttrgroupRelationEntity;
import cn.huan.mall.product.entity.AttrEntity;
import cn.huan.mall.product.entity.AttrGroupEntity;
import cn.huan.mall.product.entity.CategoryEntity;
import cn.huan.mall.product.service.AttrAttrgroupRelationService;
import cn.huan.mall.product.service.AttrService;
import cn.huan.mall.product.service.CategoryService;
import cn.huan.mall.product.vo.AttrRespVo;
import cn.huan.mall.product.vo.AttrVo;
import cn.huan.mall.product.vo.ItemDescVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Transactional
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
@Autowired
private AttrAttrgroupRelationService attrAttrgroupRelationService;
@Autowired
private CategoryService categoryService;
@Autowired
private CategoryDao categoryDao;
@Autowired
private AttrGroupDao attrGroupDao;
@Autowired
private AttrDao attrDao;
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<AttrEntity> page = this.page(
new Query<AttrEntity>().getPage(params),
new QueryWrapper<AttrEntity>()
);
return new PageUtils(page);
}
@Transactional
@Override
public void saveAttrVo(AttrVo attr) {
//保存基本信息
AttrEntity entity = new AttrEntity();
BeanUtils.copyProperties(attr, entity);
baseMapper.insert(entity);
//保存规格参数分组关联,选择了分组才保存
//基本属性才保存关联
if(attr.getAttrType() == ProductConstant.AttrType.ATTR_BASE_TYPE.getCode()){
Long groupId = attr.getAttrGroupId();
if(groupId != null){
AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
attrgroupRelationEntity.setAttrId(entity.getAttrId());
attrgroupRelationEntity.setAttrGroupId(groupId);
attrAttrgroupRelationService.save(attrgroupRelationEntity);
}
}
}
@Override
public PageUtils queryPageBase(Map<String, Object> params, Long catelogId, String attrType) {
//判断查询的是基本属性还是销售属性
QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
.eq("attr_type","base".equals(attrType)
? ProductConstant.AttrType.ATTR_BASE_TYPE.getCode()
: ProductConstant.AttrType.ATTR_SALE_TYPE.getCode()
);
if (catelogId != 0) {
//传分类id
wrapper.eq("catelog_id", catelogId);
}
String key = (String) params.get("key");
if (!StringUtils.isEmpty(key)) {
//传入了查询条件
wrapper.and(item -> item.eq("attr_id", key).or().like("attr_name", key).or().like("value_select", key));
}
IPage<AttrEntity> page = this.page(
new Query<AttrEntity>().getPage(params),
wrapper
);
List<AttrRespVo> attrRespVos = page.getRecords().stream().map(record -> {
AttrRespVo respVo = new AttrRespVo();
BeanUtils.copyProperties(record, respVo);
//查询分类名称
CategoryEntity categoryEntity = categoryDao.selectById(respVo.getCatelogId());
if (categoryEntity != null) respVo.setCatelogName(categoryEntity.getName());
//查询分组名称
//通过pms_attr_attrgroup_relation找到分组id
AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(
new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", record.getAttrId())
);
if (relationEntity != null) {
//通过分组表查询分组名称
AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
if (attrGroupEntity != null) respVo.setGroupName(attrGroupEntity.getAttrGroupName());
}
return respVo;
}).collect(Collectors.toList());
PageUtils pageUtils = new PageUtils(page);
pageUtils.setList(attrRespVos);
return pageUtils;
}
@Override
public AttrRespVo getAttrInfo(Long attrId) {
//封装响应对象
AttrRespVo respVo = new AttrRespVo();
//获取基本信息
AttrEntity entity = baseMapper.selectById(attrId);
BeanUtils.copyProperties(entity, respVo);
//设置分组路径
Long[] categoryPath = categoryService.getCategoryPath(entity.getCatelogId());
respVo.setCatelogPath(categoryPath);
//设置分组id
AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(
new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", entity.getAttrId())
);
if(relationEntity != null){
respVo.setAttrGroupId(relationEntity.getAttrGroupId());
}
return respVo;
}
@Override
public void updateInfo(AttrRespVo respVo) {
AttrEntity attrEntity = new AttrEntity();
BeanUtils.copyProperties(respVo,attrEntity);
//更新自己
baseMapper.updateById(attrEntity);
//更新所属分组
//基本属性才更新
if(respVo.getAttrType() == ProductConstant.AttrType.ATTR_BASE_TYPE.getCode()){
AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(
new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", respVo.getAttrId())
);
AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
entity.setAttrGroupId(respVo.getAttrGroupId());
entity.setAttrId(respVo.getAttrId());
if(relationEntity == null){
//不存在分组信息,添加
attrAttrgroupRelationService.save(entity);
}else{
//存在则修改
attrAttrgroupRelationService.update(
entity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", respVo.getAttrId())
);
}
}
}
@Override
public List<AttrEntity> listByGroupId(Long attrgroupId) {
//获取所有的关联基本属性,通过分组id 拿到属性id
List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.list(
new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId)
);
List<AttrEntity> attrEntities = null;
if(relationEntities != null && relationEntities.size() > 0){
//有分组的基本属性
List<Long> attrIds = relationEntities.stream().map(attr -> attr.getAttrId()).collect(Collectors.toList());
attrEntities = attrDao.selectBatchIds(attrIds);
}
return attrEntities;
}
@Override
public PageUtils queryPageNoAttrRelation(Map<String, Object> params, Long attrGroupId) {
//获取其他分类的所有关联
List<Long> otherAttrIds = attrAttrgroupRelationService.list(
new QueryWrapper<AttrAttrgroupRelationEntity>().ne("attr_group_id", attrGroupId))
.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
List<Long> exclude = new ArrayList<>(otherAttrIds);
//获取当前分类的所有关联
List<AttrEntity> currentAttrs = listByGroupId(attrGroupId);
List<Long> currentAttrIds;
if(currentAttrs != null){
currentAttrIds = currentAttrs.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
exclude.addAll(currentAttrIds);
}
//查询所有基本属性
QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
.eq("attr_type", ProductConstant.AttrType.ATTR_BASE_TYPE.getCode())
.notIn("attr_id",exclude);
IPage<AttrEntity> page = this.page(
new Query<AttrEntity>().getPage(params),
wrapper
);
return new PageUtils(page);
}
@Override
public List<Long> getSearchableId() {
return baseMapper.getSearchableId();
}
@Override
public List<ItemDescVo.BaseAttrWithGroup> getListWithGroupBySpuId(Long spuId, Long catalogId) {
return baseMapper.getListWithGroupBySpuId(spuId,catalogId);
}
} | 40.275556 | 118 | 0.661885 |
5307e74d64f0d87fda20b5cdf02ddd771333d616 | 1,371 | package com.siyuan.enjoyreading.ui.activity.knwoledge;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.androidapp.activity.BaseActivity;
import com.androidapp.smarttablayout.SmartTabLayout;
import com.androidapp.widget.CommonTitleBar;
import com.siyuan.enjoyreading.R;
import com.siyuan.enjoyreading.ui.fragment.knowledge.KnowledgeAdapter;
public class KnowledgeChapterActivity extends BaseActivity {
private CommonTitleBar mTitleBar;
private ViewPager mViewPager;
private SmartTabLayout mSmartTabLayout;
@Override
protected void initContentView(Bundle bundle) {
setContentView(R.layout.act_knowledge_main);
}
@Override
protected void initView() {
mTitleBar = findViewById(R.id.titlebar);
mViewPager = findViewById(R.id.viewpager);
mSmartTabLayout = mTitleBar.getCenterCustomView().findViewById(R.id.tab_list);
}
@Override
protected void initData() {
mViewPager.setAdapter(new KnowledgeAdapter(getSupportFragmentManager()));
mSmartTabLayout.setViewPager(mViewPager);
}
public static Intent getIntent(Context context) {
Intent intent = new Intent(context, KnowledgeChapterActivity.class);
return intent;
}
}
| 31.883721 | 87 | 0.733042 |
308c3c3ea5214a488779cc3e0fb8008ff308b9db | 967 | /*
* Copyright (c) 2019 Nike, 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.nike.cerberus.domain.environment;
import java.util.LinkedList;
public class JwtSecretData {
private LinkedList<JwtSecret> jwtSecrets = new LinkedList<>();
public LinkedList<JwtSecret> getJwtSecrets() {
return jwtSecrets;
}
public void setJwtSecrets(LinkedList<JwtSecret> jwtSecrets) {
this.jwtSecrets = jwtSecrets;
}
}
| 29.30303 | 75 | 0.726991 |
8b7a44927ac46d1629715eb0aee6e1820efc2d1f | 243 | package org.wso2.siddhi;
import org.wso2.siddhi.core.event.Event;
/**
* Proxy callback interface for QueryCallback Abstract Class
*/
public interface ExecutionPlanCallbackProxy {
void receive(long l, Event[] events, Event[] events1);
} | 24.3 | 60 | 0.757202 |
7a60c944224ad37f3c3693f6260dcb655f31c9ca | 2,894 | /**
* 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.meecrowave.tests.ssl;
import static org.junit.Assert.assertEquals;
import java.nio.file.Paths;
import java.util.Properties;
import org.apache.meecrowave.Meecrowave.Builder;
import org.apache.meecrowave.junit.MeecrowaveRule;
import org.junit.ClassRule;
import org.junit.Test;
/*
* Creates the following connector
* <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" scheme="https" secure="true"
sslDefaultHost="_default_">
<SSLHostConfig honorCipherOrder="false" hostName="_default_">
<Certificate certificateKeystoreFile="meecrowave.jks"
certificateKeystorePassword="meecrowave"
certificateKeyAlias="meecrowave"
truststoreFile = "meecrowave.jks"
truststorePassword = "meecrowave"/>
</SSLHostConfig>
</Connector>
*/
public class SslDefaultConfigurationTest {
private static final String keyStorePath = "meecrowave_first_host.jks";
static {
System.setProperty("javax.net.ssl.trustStore", Paths.get("").toAbsolutePath() + "/target/classes/meecrowave_trust.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "meecrowave");
}
public static final Properties p = new Properties() {{
setProperty("connector.sslhostconfig.truststoreFile", "meecrowave_trust.jks");
setProperty("connector.sslhostconfig.truststorePassword", "meecrowave");
}};
@ClassRule
public static final MeecrowaveRule CONTAINER =
new MeecrowaveRule(new Builder() {{
randomHttpsPort();
setSkipHttp(true);
includePackages("org.apache.meecrowave.tests.ssl");
setSsl(true);
setKeystoreFile(keyStorePath);
setKeyAlias("meecrowave");
setKeystorePass("meecrowave");
setProperties(p);
}}, "");
@Test
public void run() {
assertEquals("Hello", TestSetup.callJaxrsService(CONTAINER.getConfiguration().getHttpsPort()));
}
}
| 37.584416 | 152 | 0.681064 |
ffcc486302e1891f681d63dc21f620e05f30e70e | 4,451 | package com.borneo.framework.common.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class UploadFileUtil {
private static final String SLASH = "/";
public static void uploadFile(CommonsMultipartFile uploadedFile, String fileName, String uploadFilePath, String destFileFolder) {
try {
File directory = createDirectory(uploadFilePath, destFileFolder);
File dstFile = new File(directory.getAbsolutePath() + File.separator + fileName);
FileOutputStream outputStream = null;
outputStream = new FileOutputStream(dstFile);
outputStream.write(uploadedFile.getFileItem().get());
outputStream.close();
// PhotoUtils.resizeImage_java(directory.getAbsolutePath() + File.separator + fileName, directory.getAbsolutePath() + File.separator + imgTo, height, width);
/*
* InputStream in = uploadedFile.getInputStream(); OutputStream out = new FileOutputStream(dstFile); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close();
*/
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void uploadFile(CommonsMultipartFile uploadedFile, String fileName, String imgTo, int height, int width, String uploadFilePath, String destFileFolder) {
try {
File directory = createDirectory(uploadFilePath, destFileFolder);
File dstFile = new File(directory.getAbsolutePath() + File.separator + fileName);
FileOutputStream outputStream = null;
outputStream = new FileOutputStream(dstFile);
outputStream.write(uploadedFile.getFileItem().get());
outputStream.close();
// PhotoUtils.resizeImage_java(directory.getAbsolutePath() + File.separator + fileName, directory.getAbsolutePath() + File.separator + imgTo, height, width);
/*
* InputStream in = uploadedFile.getInputStream(); OutputStream out = new FileOutputStream(dstFile); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close();
*/
} catch (Exception ex) {
ex.printStackTrace();
}
}
// public static void uploadFile(BufferedImage image, String type, String fileName,String uploadFilePath,String destFileFolder)
// {
// try
// {
// File directory = createDirectory(uploadFilePath, destFileFolder);
//
// File dstFile = new File(directory.getAbsolutePath()+File.separator+ fileName);
//
// ImageIO.write(image, type, dstFile);
//
//
// }
// catch(Exception ex)
// {
// ex.printStackTrace();
// }
// }
public static File createDirectory(String path, String name) throws Exception {
File dir = new File(path + File.separator + name);
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
public static String getFileExtension(String fileName) throws Exception {
int dotPos = fileName.lastIndexOf(".");
String extension = fileName.substring(dotPos);
return extension;
}
public static String getFullPath(String name, String path, String folder) throws Exception {
File dir = new File(path + SLASH + folder + SLASH + name);
String fullPath = "";
if (dir.exists()) {
fullPath = dir.getAbsolutePath(); //path+SLASH+folder+SLASH+name; dir.getAbsolutePath();
//System.out.print("fullPath:"+dir.getAbsolutePath());
//dir.mkdirs();
} else {
System.out.println("error");
}
return fullPath;
}
public static void copyBytes(InputStream input,OutputStream output,int bufferSize) throws IOException {
byte[] buf = new byte[bufferSize];
int bytesRead = input.read(buf);
while (bytesRead != -1) {
output.write(buf, 0, bytesRead);
bytesRead = input.read(buf);
}
output.flush();
}
}
| 38.37069 | 269 | 0.619411 |
4763f2ce2813cc47ad90bb27b5fd9aa14e6ff347 | 2,862 | /*
* 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.jena.riot.writer;
import java.util.Collection;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.Triple;
import org.apache.jena.riot.system.PrefixMap;
import static org.apache.jena.riot.writer.WriterConst.RDF_type;
/**
* Calculate widths to print in.
* <p>
* Flag {@code hasPrefixForRDF} is to avoid a reverse lookup in a prefix map.
*/
/*package*/ class Widths {
/*package*/ static int calcWidth(PrefixMap prefixMap, String baseURI, Node p, boolean printTypeKeyword) {
String x = prefixMap.abbreviate(p.getURI());
if ( x == null )
return p.getURI().length() + 2;
if ( printTypeKeyword && RDF_type.equals(p) ) {
// Use "a".
return 1;
}
return x.length();
}
/*package*/ static int calcWidth(PrefixMap prefixMap, String baseURI, Collection<Node> nodes, int minWidth, int maxWidth, boolean printTypeKeyword) {
Node prev = null;
int nodeMaxWidth = minWidth;
for ( Node n : nodes ) {
if ( prev != null && prev.equals(n) )
continue;
int len = calcWidth(prefixMap, baseURI, n, printTypeKeyword);
if ( len > maxWidth )
continue;
if ( nodeMaxWidth < len )
nodeMaxWidth = len;
prev = n;
}
return nodeMaxWidth;
}
/*package*/ static int calcWidthTriples(PrefixMap prefixMap, String baseURI, Collection<Triple> triples, int minWidth, int maxWidth, boolean printTypeKeyword) {
Node prev = null;
int nodeMaxWidth = minWidth;
for ( Triple triple : triples ) {
Node n = triple.getPredicate();
if ( prev != null && prev.equals(n) )
continue;
int len = calcWidth(prefixMap, baseURI, n, printTypeKeyword);
if ( len > maxWidth )
continue;
if ( nodeMaxWidth < len )
nodeMaxWidth = len;
prev = n;
}
return nodeMaxWidth;
}
}
| 35.333333 | 164 | 0.628232 |
1739333d0b32969b0b233336eb153607fad6c83c | 2,988 | /*
* Copyright 2011 JBoss 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.drools.guvnor.server.util;
import org.apache.commons.lang.StringUtils;
import org.drools.guvnor.client.rpc.AssetPageRow;
import org.drools.repository.AssetItem;
import org.drools.guvnor.client.rpc.Asset;
import org.drools.guvnor.client.rpc.Path;
import org.drools.guvnor.client.rpc.PathImpl;
public class AssetPageRowPopulator {
public AssetPageRow populateFrom(AssetItem assetItem) {
AssetPageRow row = new AssetPageRow();
//REVISIT: get a Path instance from drools-repository-vfs
Path path = new PathImpl();
path.setUUID(assetItem.getUUID());
row.setPath( path );
row.setFormat( assetItem.getFormat() );
row.setName( assetItem.getName() );
row.setDescription( assetItem.getDescription() );
row.setAbbreviatedDescription( StringUtils.abbreviate( assetItem.getDescription(), 80 ) );
row.setStateName( assetItem.getStateDescription() );
row.setCreator( assetItem.getCreator() );
row.setCreatedDate( assetItem.getCreatedDate().getTime() );
row.setLastContributor( assetItem.getLastContributor() );
row.setLastModified( assetItem.getLastModified().getTime() );
row.setCategorySummary( assetItem.getCategorySummary() );
row.setExternalSource( assetItem.getExternalSource() );
row.setDisabled( assetItem.getDisabled() );
row.setValid(assetItem.getValid());
return row;
}
public AssetPageRow populateFrom(Asset asset) {
AssetPageRow row = new AssetPageRow();
row.setPath( asset.getPath() );
row.setFormat( asset.getFormat() );
row.setName( asset.getName() );
row.setDescription( asset.getDescription() );
row.setAbbreviatedDescription( StringUtils.abbreviate( asset.getDescription(), 80 ) );
row.setStateName( asset.getState() );
row.setCreator( asset.getLastContributor() );
row.setCreatedDate( asset.getDateCreated() );
row.setLastContributor( asset.getLastContributor() );
row.setLastModified( asset.getLastModified() );
//TODO:
//row.setCategorySummary( asset.getMetaData().getCategories() );
row.setExternalSource( asset.getMetaData().getExternalSource() );
row.setDisabled( asset.getMetaData().isDisabled() );
row.setValid(asset.getMetaData().getValid());
return row;
}
}
| 44.597015 | 98 | 0.695448 |
fe70fdaf807dc4c920933deb302951cf938c8921 | 5,236 | package com.vladsch.flexmark.ext.enumerated.reference.internal;
import com.vladsch.flexmark.ext.attributes.internal.AttributesNodeFormatter;
import com.vladsch.flexmark.ext.enumerated.reference.*;
import com.vladsch.flexmark.formatter.*;
import com.vladsch.flexmark.util.data.DataHolder;
import com.vladsch.flexmark.util.format.options.ElementPlacement;
import com.vladsch.flexmark.util.format.options.ElementPlacementSort;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class EnumeratedReferenceNodeFormatter extends NodeRepositoryFormatter<EnumeratedReferenceRepository, EnumeratedReferenceBlock, EnumeratedReferenceText> {
private final EnumeratedReferenceFormatOptions options;
public EnumeratedReferenceNodeFormatter(DataHolder options) {
super(options, null, AttributesNodeFormatter.ATTRIBUTE_UNIQUIFICATION_CATEGORY_MAP);
this.options = new EnumeratedReferenceFormatOptions(options);
}
@Override
public EnumeratedReferenceRepository getRepository(DataHolder options) {
return EnumeratedReferenceExtension.ENUMERATED_REFERENCES.get(options);
}
@Override
public ElementPlacement getReferencePlacement() {
return options.enumeratedReferencePlacement;
}
@Override
public ElementPlacementSort getReferenceSort() {
return options.enumeratedReferenceSort;
}
@Override
protected void renderReferenceBlock(EnumeratedReferenceBlock node, NodeFormatterContext context, MarkdownWriter markdown) {
markdown.blankLine().append("[@").appendNonTranslating(node.getText()).append("]: ");
markdown.pushPrefix().addPrefix(" ", true);
context.renderChildren(node);
markdown.popPrefix();
markdown.blankLine();
}
@Nullable
@Override
public Set<NodeFormattingHandler<?>> getNodeFormattingHandlers() {
return new HashSet<>(Arrays.asList(
new NodeFormattingHandler<>(EnumeratedReferenceText.class, EnumeratedReferenceNodeFormatter.this::render),
new NodeFormattingHandler<>(EnumeratedReferenceLink.class, EnumeratedReferenceNodeFormatter.this::render),
new NodeFormattingHandler<>(EnumeratedReferenceBlock.class, EnumeratedReferenceNodeFormatter.this::render)
));
}
@Nullable
@Override
public Set<Class<?>> getNodeClasses() {
if (options.enumeratedReferencePlacement != ElementPlacement.AS_IS && options.enumeratedReferenceSort != ElementPlacementSort.SORT_UNUSED_LAST) return null;
// noinspection ArraysAsListWithZeroOrOneArgument
return new HashSet<>(Arrays.asList(
EnumeratedReferenceBlock.class
));
}
private void render(EnumeratedReferenceBlock node, NodeFormatterContext context, MarkdownWriter markdown) {
renderReference(node, context, markdown);
}
private static void renderReferenceText(BasedSequence text, NodeFormatterContext context, MarkdownWriter markdown) {
if (!text.isEmpty()) {
BasedSequence valueChars = text;
int pos = valueChars.indexOf(':');
String category;
String id = null;
if (pos == -1) {
category = text.toString();
} else {
category = valueChars.subSequence(0, pos).toString();
id = valueChars.subSequence(pos + 1).toString();
}
String encoded = AttributesNodeFormatter.getEncodedIdAttribute(category, id, context, markdown);
markdown.append(encoded);
}
}
private void render(EnumeratedReferenceText node, NodeFormatterContext context, MarkdownWriter markdown) {
markdown.append("[#");
if (context.isTransformingText()) {
renderReferenceText(node.getText(), context, markdown);
} else {
context.renderChildren(node);
}
markdown.append("]");
}
private void render(EnumeratedReferenceLink node, NodeFormatterContext context, MarkdownWriter markdown) {
markdown.append("[@");
if (context.isTransformingText()) {
renderReferenceText(node.getText(), context, markdown);
} else {
context.renderChildren(node);
}
markdown.append("]");
}
public static class Factory implements NodeFormatterFactory {
@NotNull
@Override
public NodeFormatter create(@NotNull DataHolder options) {
return new EnumeratedReferenceNodeFormatter(options);
}
@Nullable
@Override
public Set<Class<?>> getAfterDependents() {
// run before attributes formatter so categories are uniquified first
// renderers are sorted in reverse order for backward compatibility
Set<Class<?>> aSet = new HashSet<>();
aSet.add(AttributesNodeFormatter.Factory.class);
return aSet;
}
@Nullable
@Override
public Set<Class<?>> getBeforeDependents() {
return null;
}
}
}
| 38.5 | 164 | 0.688503 |
e0673bc02722cac802a86ea8354cd7772875ae33 | 1,530 | /*
* 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.beam.runners.core.metrics;
import java.io.Serializable;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.annotations.Experimental.Kind;
/**
* A {@link MetricCell} is used for accumulating in-memory changes to a metric. It represents a
* specific metric name in a single context.
*
* @param <DataT> The type of metric data stored (and extracted) from this cell.
*/
@Experimental(Kind.METRICS)
public interface MetricCell<DataT> extends Serializable {
/**
* Return the {@link DirtyState} tracking whether this metric cell contains uncommitted changes.
*/
DirtyState getDirty();
/** Return the cumulative value of this metric. */
DataT getCumulative();
}
| 38.25 | 98 | 0.752288 |
5317d0f5dabaef689479c64a6012e0188a404a39 | 2,299 | package edu.tamu.aser.tests.ABPushPop; /*************************************************************/
/* (C) IBM Corporation (2007), ALL RIGHTS RESERVED */
/* */
/* Benny Godlin 30/1/2007 Class created */
/*************************************************************/
// Note: ConTest only version - not part of CMGTT
public class Names {
public static String delim;
public static String ext;
public static String baseDir;
public static void setBaseDir(String _baseDir) {
delim = System.getProperty("file.separator");
baseDir = _baseDir + delim;
ext = ".jso";
}
public static String initProbFile() {
return baseDir + "ProbTable_init" + ext;
}
public static String seriesDir(int seriesIndex) {
return baseDir + "series"+ seriesIndex;
}
public static String probFile(int seriesIndex) {
return seriesDir(seriesIndex) + delim + "ProbTable_s"+ seriesIndex + ext;
}
public static String runPathFile(int seriesIndex, int pathIndex) {
return seriesDir(seriesIndex) + delim + "RunPath_s"+ seriesIndex +"_r"+ pathIndex + ext;
}
public static String runResultsFile(int seriesIndex) {
return seriesDir(seriesIndex) + delim + "RunResults_s"+ seriesIndex + ext;
}
public static String threadName(Object codeObj, int seriesIndex, int runIndex) {
String className = codeObj.getClass().getName();
return "testedThread_"+ className +"_s"+ seriesIndex +"_r"+ runIndex;
}
public static String threadName(Object codeObj, int num, int seriesIndex, int runIndex) {
String className = codeObj.getClass().getName();
return "testedThread_"+ className +"_"+ num +"_s"+ seriesIndex +"_r"+ runIndex;
}
// static name - without the seriesIndex and runIndex
public static String threadName(Object codeObj) {
String className = codeObj.getClass().getName();
return "testedThread_"+ className;
}
// static name - without the seriesIndex and runIndex
public static String threadName(Object codeObj, int num) {
String className = codeObj.getClass().getName();
return "testedThread_"+ className +"_"+ num;
}
}
| 37.080645 | 102 | 0.606351 |
cd41e7b50a44a913e60bfa78aa5050df84296298 | 608 | package com.gangoffour2.monopoly.azioni.giocatore;
import com.gangoffour2.monopoly.model.giocatore.Giocatore;
import com.gangoffour2.monopoly.stati.casella.StatoCasella;
import com.gangoffour2.monopoly.stati.partita.StatoPartita;
import lombok.Data;
import lombok.experimental.SuperBuilder;
import java.io.Serializable;
@Data
@SuperBuilder
public abstract class AzioneGiocatore implements Serializable {
protected Giocatore giocatore;
protected AzioneGiocatore() {
}
public abstract void accept(StatoCasella statoCasella);
public abstract void accept(StatoPartita statoPartita);
}
| 25.333333 | 63 | 0.8125 |
36ffe2755bf80e4bf3091ac777d688508004e35a | 4,017 | /*
* 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.aliyuncs.live.transform.v20161101;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.live.model.v20161101.DescribeLiveSnapshotDetectPornConfigResponse;
import com.aliyuncs.live.model.v20161101.DescribeLiveSnapshotDetectPornConfigResponse.LiveSnapshotDetectPornConfig;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeLiveSnapshotDetectPornConfigResponseUnmarshaller {
public static DescribeLiveSnapshotDetectPornConfigResponse unmarshall(DescribeLiveSnapshotDetectPornConfigResponse describeLiveSnapshotDetectPornConfigResponse, UnmarshallerContext _ctx) {
describeLiveSnapshotDetectPornConfigResponse.setRequestId(_ctx.stringValue("DescribeLiveSnapshotDetectPornConfigResponse.RequestId"));
describeLiveSnapshotDetectPornConfigResponse.setPageNum(_ctx.integerValue("DescribeLiveSnapshotDetectPornConfigResponse.PageNum"));
describeLiveSnapshotDetectPornConfigResponse.setOrder(_ctx.stringValue("DescribeLiveSnapshotDetectPornConfigResponse.Order"));
describeLiveSnapshotDetectPornConfigResponse.setTotalPage(_ctx.integerValue("DescribeLiveSnapshotDetectPornConfigResponse.TotalPage"));
describeLiveSnapshotDetectPornConfigResponse.setPageSize(_ctx.integerValue("DescribeLiveSnapshotDetectPornConfigResponse.PageSize"));
describeLiveSnapshotDetectPornConfigResponse.setTotalNum(_ctx.integerValue("DescribeLiveSnapshotDetectPornConfigResponse.TotalNum"));
List<LiveSnapshotDetectPornConfig> liveSnapshotDetectPornConfigList = new ArrayList<LiveSnapshotDetectPornConfig>();
for (int i = 0; i < _ctx.lengthValue("DescribeLiveSnapshotDetectPornConfigResponse.LiveSnapshotDetectPornConfigList.Length"); i++) {
LiveSnapshotDetectPornConfig liveSnapshotDetectPornConfig = new LiveSnapshotDetectPornConfig();
liveSnapshotDetectPornConfig.setOssObject(_ctx.stringValue("DescribeLiveSnapshotDetectPornConfigResponse.LiveSnapshotDetectPornConfigList["+ i +"].OssObject"));
liveSnapshotDetectPornConfig.setAppName(_ctx.stringValue("DescribeLiveSnapshotDetectPornConfigResponse.LiveSnapshotDetectPornConfigList["+ i +"].AppName"));
liveSnapshotDetectPornConfig.setInterval(_ctx.integerValue("DescribeLiveSnapshotDetectPornConfigResponse.LiveSnapshotDetectPornConfigList["+ i +"].Interval"));
liveSnapshotDetectPornConfig.setOssBucket(_ctx.stringValue("DescribeLiveSnapshotDetectPornConfigResponse.LiveSnapshotDetectPornConfigList["+ i +"].OssBucket"));
liveSnapshotDetectPornConfig.setDomainName(_ctx.stringValue("DescribeLiveSnapshotDetectPornConfigResponse.LiveSnapshotDetectPornConfigList["+ i +"].DomainName"));
liveSnapshotDetectPornConfig.setOssEndpoint(_ctx.stringValue("DescribeLiveSnapshotDetectPornConfigResponse.LiveSnapshotDetectPornConfigList["+ i +"].OssEndpoint"));
List<String> scenes = new ArrayList<String>();
for (int j = 0; j < _ctx.lengthValue("DescribeLiveSnapshotDetectPornConfigResponse.LiveSnapshotDetectPornConfigList["+ i +"].Scenes.Length"); j++) {
scenes.add(_ctx.stringValue("DescribeLiveSnapshotDetectPornConfigResponse.LiveSnapshotDetectPornConfigList["+ i +"].Scenes["+ j +"]"));
}
liveSnapshotDetectPornConfig.setScenes(scenes);
liveSnapshotDetectPornConfigList.add(liveSnapshotDetectPornConfig);
}
describeLiveSnapshotDetectPornConfigResponse.setLiveSnapshotDetectPornConfigList(liveSnapshotDetectPornConfigList);
return describeLiveSnapshotDetectPornConfigResponse;
}
} | 69.258621 | 189 | 0.839432 |
93e8992e0b9f6f3bda4c2d9a97cbab8161fabf06 | 13,684 | /*
* Copyright 2021 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 io.mateo.cxf.codegen.wsdl2java;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.gradle.api.GradleException;
import org.gradle.api.Named;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.file.ProjectLayout;
import org.gradle.api.file.RegularFile;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.SetProperty;
/**
* Default implementation for options for the {@code wsdl2java} command.
*/
public class WsdlOption implements Option, Named {
private final String name;
private final RegularFileProperty wsdl;
private final ListProperty<String> packageNames;
private final ListProperty<String> extraArgs;
private final ListProperty<String> xjcArgs;
private final ListProperty<String> asyncMethods;
private final ListProperty<String> bareMethods;
private final ListProperty<String> mimeMethods;
private final ListProperty<String> namespaceExcludes;
private final Property<Boolean> defaultExcludesNamespace;
private final Property<Boolean> defaultNamespacePackageMapping;
private final SetProperty<String> bindingFiles;
private final Property<String> wsdlLocation;
private final Property<Boolean> wsdlList;
private final Property<String> frontend;
private final Property<String> databinding;
private final Property<String> wsdlVersion;
private final Property<String> catalog;
private final Property<Boolean> extendedSoapHeaders;
private final Property<String> validateWsdl;
private final Property<Boolean> noTypes;
private final Property<String> faultSerialVersionUid;
private final Property<String> exceptionSuper;
private final ListProperty<String> seiSuper;
private final Property<Boolean> markGenerated;
private final Property<Boolean> suppressGeneratedDate;
private final Property<String> serviceName;
private final Property<Boolean> autoNameResolution;
private final Property<Boolean> noAddressBinding;
private final Property<Boolean> allowElementRefs;
private final Property<String> encoding;
private final Property<Boolean> verbose;
private final DirectoryProperty outputDir;
private final ProjectLayout layout;
@Inject
public WsdlOption(String name, ObjectFactory objects, ProjectLayout layout) {
this.name = name;
this.layout = layout;
this.outputDir = objects.directoryProperty()
.convention(layout.getBuildDirectory().dir("generated-sources/cxf/" + name));
this.wsdl = objects.fileProperty();
this.packageNames = objects.listProperty(String.class);
this.extraArgs = objects.listProperty(String.class);
this.xjcArgs = objects.listProperty(String.class);
this.asyncMethods = objects.listProperty(String.class);
this.bareMethods = objects.listProperty(String.class);
this.mimeMethods = objects.listProperty(String.class);
this.namespaceExcludes = objects.listProperty(String.class);
this.defaultExcludesNamespace = objects.property(Boolean.class);
this.defaultNamespacePackageMapping = objects.property(Boolean.class);
this.bindingFiles = objects.setProperty(String.class);
this.wsdlLocation = objects.property(String.class);
this.wsdlList = objects.property(Boolean.class);
this.frontend = objects.property(String.class);
this.databinding = objects.property(String.class);
this.wsdlVersion = objects.property(String.class);
this.catalog = objects.property(String.class);
this.extendedSoapHeaders = objects.property(Boolean.class);
this.validateWsdl = objects.property(String.class);
this.noTypes = objects.property(Boolean.class);
this.faultSerialVersionUid = objects.property(String.class);
this.exceptionSuper = objects.property(String.class);
this.seiSuper = objects.listProperty(String.class);
this.markGenerated = objects.property(Boolean.class);
this.suppressGeneratedDate = objects.property(Boolean.class);
this.serviceName = objects.property(String.class);
this.autoNameResolution = objects.property(Boolean.class);
this.noAddressBinding = objects.property(Boolean.class);
this.allowElementRefs = objects.property(Boolean.class);
this.encoding = objects.property(String.class);
this.verbose = objects.property(Boolean.class);
}
/**
* {@inheritDoc}
*/
@Override
public RegularFileProperty getWsdl() {
return this.wsdl;
}
/**
* {@inheritDoc}
*/
@Override
public ListProperty<String> getPackageNames() {
return this.packageNames;
}
/**
* {@inheritDoc}
*/
@Override
public ListProperty<String> getExtraArgs() {
return this.extraArgs;
}
/**
* {@inheritDoc}
*/
@Override
public ListProperty<String> getXjcArgs() {
return this.xjcArgs;
}
/**
* {@inheritDoc}
*/
@Override
public ListProperty<String> getAsyncMethods() {
return this.asyncMethods;
}
/**
* {@inheritDoc}
*/
@Override
public ListProperty<String> getBareMethods() {
return this.bareMethods;
}
/**
* {@inheritDoc}
*/
@Override
public ListProperty<String> getMimeMethods() {
return this.mimeMethods;
}
/**
* {@inheritDoc}
*/
@Override
public ListProperty<String> getNamespaceExcludes() {
return this.namespaceExcludes;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getDefaultExcludesNamespace() {
return this.defaultExcludesNamespace;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getDefaultNamespacePackageMapping() {
return this.defaultNamespacePackageMapping;
}
/**
* {@inheritDoc}
*/
@Override
public SetProperty<String> getBindingFiles() {
return this.bindingFiles;
}
/**
* {@inheritDoc}
*/
@Override
public Property<String> getWsdlLocation() {
return this.wsdlLocation;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getWsdlList() {
return this.wsdlList;
}
/**
* {@inheritDoc}
*/
@Override
public Property<String> getFrontend() {
return this.frontend;
}
/**
* {@inheritDoc}
*/
@Override
public Property<String> getDatabinding() {
return this.databinding;
}
/**
* {@inheritDoc}
*/
@Override
public Property<String> getWsdlVersion() {
return this.wsdlVersion;
}
/**
* {@inheritDoc}
*/
@Override
public Property<String> getCatalog() {
return this.catalog;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getExtendedSoapHeaders() {
return this.extendedSoapHeaders;
}
/**
* {@inheritDoc}
*/
@Override
public Property<String> getValidateWsdl() {
return this.validateWsdl;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getNoTypes() {
return this.noTypes;
}
/**
* {@inheritDoc}
*/
@Override
public Property<String> getFaultSerialVersionUid() {
return this.faultSerialVersionUid;
}
/**
* {@inheritDoc}
*/
@Override
public Property<String> getExceptionSuper() {
return this.exceptionSuper;
}
/**
* {@inheritDoc}
*/
@Override
public ListProperty<String> getSeiSuper() {
return this.seiSuper;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getMarkGenerated() {
return this.markGenerated;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getSuppressGeneratedDate() {
return this.suppressGeneratedDate;
}
/**
* {@inheritDoc}
*/
@Override
public Property<String> getServiceName() {
return this.serviceName;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getAutoNameResolution() {
return this.autoNameResolution;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getNoAddressBinding() {
return this.noAddressBinding;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getAllowElementRefs() {
return this.allowElementRefs;
}
/**
* {@inheritDoc}
*/
@Override
public Property<String> getEncoding() {
return this.encoding;
}
/**
* {@inheritDoc}
*/
@Override
public Property<Boolean> getVerbose() {
return this.verbose;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public DirectoryProperty getOutputDir() {
return this.outputDir;
}
/**
* Generate arguments for {@code wsdl2java}.
* @return arguments
*/
public List<String> generateArgs() {
List<String> command = new ArrayList<>();
if (this.encoding.isPresent()) {
command.add("-encoding");
command.add(this.encoding.get());
}
if (this.packageNames.isPresent()) {
this.packageNames.get().forEach((value) -> {
command.add("-p");
command.add(value);
});
}
if (this.namespaceExcludes.isPresent()) {
this.namespaceExcludes.get().forEach((value) -> {
command.add("-nexclude");
command.add(value);
});
}
command.add("-d");
command.add(this.outputDir.get().getAsFile().getAbsolutePath()); // always set by
// convention
if (this.bindingFiles.isPresent()) {
this.bindingFiles.get().forEach((value) -> {
RegularFile bindingFile = this.layout.getProjectDirectory().file(value);
command.add("-b");
command.add(bindingFile.getAsFile().toURI().toString());
});
}
if (this.frontend.isPresent()) {
command.add("-fe");
command.add(this.frontend.get());
}
if (this.databinding.isPresent()) {
command.add("-db");
command.add(this.databinding.get());
}
if (this.wsdlVersion.isPresent()) {
command.add("-wv");
command.add(this.wsdlVersion.get());
}
if (this.catalog.isPresent()) {
command.add("-catalog");
command.add(this.catalog.get());
}
if (this.extendedSoapHeaders.isPresent() && this.extendedSoapHeaders.get()) {
command.add("-exsh");
command.add("true");
}
if (this.noTypes.isPresent() && this.noTypes.get()) {
command.add("-noTypes");
}
if (this.allowElementRefs.isPresent() && this.allowElementRefs.get()) {
command.add("-allowElementReferences");
}
if (this.validateWsdl.isPresent()) {
command.add("-validate=" + this.validateWsdl.get());
}
if (this.markGenerated.isPresent() && this.markGenerated.get()) {
command.add("-mark-generated");
}
if (this.suppressGeneratedDate.isPresent() && this.suppressGeneratedDate.get()) {
command.add("-suppress-generated-date");
}
if (this.defaultExcludesNamespace.isPresent()) {
command.add("-dex");
command.add(this.defaultExcludesNamespace.get().toString());
}
if (this.defaultNamespacePackageMapping.isPresent()) {
command.add("-dns");
command.add(this.defaultNamespacePackageMapping.get().toString());
}
if (this.serviceName.isPresent()) {
command.add("-sn");
command.add(this.serviceName.get());
}
if (this.faultSerialVersionUid.isPresent()) {
command.add("-faultSerialVersionUID");
command.add(this.faultSerialVersionUid.get());
}
if (this.exceptionSuper.isPresent()) {
command.add("-exceptionSuper");
command.add(this.exceptionSuper.get());
}
if (this.seiSuper.isPresent()) {
this.seiSuper.get().forEach((value) -> {
command.add("-seiSuper");
command.add(value);
});
}
if (this.autoNameResolution.isPresent() && this.autoNameResolution.get()) {
command.add("-autoNameResolution");
}
if (this.noAddressBinding.isPresent() && this.noAddressBinding.get()) {
command.add("-noAddressBinding");
}
if (this.xjcArgs.isPresent()) {
this.xjcArgs.get().forEach((value) -> {
command.add("-xjc" + value);
});
}
if (this.extraArgs.isPresent()) {
command.addAll(this.extraArgs.get());
}
if (this.wsdlLocation.isPresent()) {
command.add("-wsdlLocation");
command.add(this.wsdlLocation.get());
}
if (this.wsdlList.isPresent() && this.wsdlList.get()) {
command.add("-wsdlList");
}
if (this.verbose.isPresent() && this.verbose.get()) {
command.add("-verbose");
}
if (this.asyncMethods.isPresent() && !this.asyncMethods.get().isEmpty()) {
StringBuilder sb = new StringBuilder("-asyncMethods");
sb.append("=");
boolean first = true;
for (String value : this.asyncMethods.get()) {
if (!first) {
sb.append(",");
}
sb.append(value);
first = false;
}
command.add(sb.toString());
}
if (this.bareMethods.isPresent() && !this.bareMethods.get().isEmpty()) {
StringBuilder sb = new StringBuilder("-bareMethods");
sb.append("=");
boolean first = true;
for (String value : this.bareMethods.get()) {
if (!first) {
sb.append(",");
}
sb.append(value);
first = false;
}
command.add(sb.toString());
}
if (this.mimeMethods.isPresent() && !this.mimeMethods.get().isEmpty()) {
StringBuilder sb = new StringBuilder("-mimeMethods");
sb.append("=");
boolean first = true;
for (String value : this.mimeMethods.get()) {
if (!first) {
sb.append(",");
}
sb.append(value);
first = false;
}
command.add(sb.toString());
}
if (!this.wsdl.isPresent()) {
throw new GradleException("'wsdl' property is not present");
}
command.add(this.wsdl.get().getAsFile().toURI().toString());
return command;
}
}
| 23.798261 | 83 | 0.697822 |
425f1cf19abf933664a6d2066b9182b5ce18f418 | 585 | package com.mtons.mblog.modules.service;
import com.mtons.mblog.modules.data.NotifyVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
/**
* @author langhsu on 2015/8/31.
*/
public interface NotifyService {
Page<NotifyVO> findByOwnId(Pageable pageable, long ownId);
/**
* 发送通知
* @param notify
*/
void send(NotifyVO notify);
/**
* 未读消息数量
* @param ownId
* @return
*/
int unread4Me(long ownId);
/**
* 标记为已读
* @param ownId
*/
void readed4Me(long ownId);
}
| 17.205882 | 62 | 0.62735 |
21c078bdbec9f4285ef609da3d24ba2d6a92487b | 17,876 | package de.unistuttgart.ipvs.as.mmp.init;
import com.google.common.io.ByteStreams;
import de.unistuttgart.ipvs.as.mmp.common.domain.*;
import de.unistuttgart.ipvs.as.mmp.common.domain.opcua.OpcuaInformationModel;
import de.unistuttgart.ipvs.as.mmp.common.domain.opcua.OpcuaMetadata;
import de.unistuttgart.ipvs.as.mmp.common.pmml.PMMLMetadataParser;
import de.unistuttgart.ipvs.as.mmp.common.repository.DBFileRepository;
import de.unistuttgart.ipvs.as.mmp.common.repository.ProjectRepository;
import de.unistuttgart.ipvs.as.mmp.common.repository.UserRepository;
import de.unistuttgart.ipvs.as.mmp.common.util.DefaultDataBuilder;
import de.unistuttgart.ipvs.as.mmp.eam.domain.BusinessProcess;
import de.unistuttgart.ipvs.as.mmp.eam.domain.EAMContainer;
import de.unistuttgart.ipvs.as.mmp.eam.domain.OrganisationUnit;
import de.unistuttgart.ipvs.as.mmp.eam.repository.BusinessProcessRepository;
import de.unistuttgart.ipvs.as.mmp.eam.repository.EAMContainerRepository;
import de.unistuttgart.ipvs.as.mmp.eam.repository.OrganisationUnitRepository;
import de.unistuttgart.ipvs.as.mmp.model.repository.ModelFileRepository;
import de.unistuttgart.ipvs.as.mmp.model.repository.ModelRepository;
import de.unistuttgart.ipvs.as.mmp.model.repository.OpcuaInformationModelRepository;
import de.unistuttgart.ipvs.as.mmp.model.service.OpcuaInformationModelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
@Component
@Transactional
public class DatabaseInitializer implements ApplicationListener<ApplicationStartedEvent> {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Value("${spring.profiles.active}")
private String activeProfile;
@Value("${database.production.init}")
private boolean isInitProductionData;
private final ModelRepository modelRepository;
private final UserRepository userRepository;
private final ProjectRepository projectRepository;
private final ModelFileRepository modelFileRepository;
private final BusinessProcessRepository businessProcessRepository;
private final OrganisationUnitRepository organisationUnitRepository;
private final EAMContainerRepository eamContainerRepository;
private final DBFileRepository dbFileRepository;
private final OpcuaInformationModelService opcuaInformationModelService;
private final OpcuaInformationModelRepository opcuaInformationModelRepository;
private PMMLMetadataParser pmmlMetadataParser = new PMMLMetadataParser();
private ResourceLoader resourceLoader;
private static final String[] projectUseCases = {"Predictive Maintenance", "Predictive Quality",
"Root Cause Analysis", "Lead Time Improvement"};
private static final List<String> projectDescriptionPrefixes = Arrays.asList("New", "Old", "Best", "Even better",
"Rather bad", "Medium", "Excellent", "Test", "Mediocre", "Rather good", "An even better", "Special",
"Slightly better", "Perfect", "An even worse", "Not sure about that");
private static final List<String> modelNamePrefixes = Arrays.asList("Predictive", "Clustering", "Best", "Even better",
"Rather bad", "Medium", "Excellent", "Test", "Mediocre", "Super-slow", "Rather good", "An even better",
"Performant", "Special", "Not usable", "Usable", "Slightly better", "Perfect", "Super-fast",
"An even worse", "Not sure about that", "Still better than the previous", "Accidentally created");
private static final List<String> algorithmNames = Arrays.asList("J48", "Simple Logistic Regression", "rpart", "randomForest",
"RProp", "Naive Bayes", "Multilayer Perceptron", "Linear Regression", "Hoeffding Tree");
private static final String[] eamBusinessProcesses = {"Development", "Purchasing", "Marketing", "Acquire orders",
"Production", "Sales", "Shipping", "After Sales"};
private static final String[] orgUnitNames = {"Neukirch", "Berlin", "Ditzingen", "Karlsruhe", "Teningen", "Aachen",
"München-Unterföhring", "Hettingen", "Gerlingen", "Stuttgart"};
private static final String[] opcuaFiles = {"informationModel_laserMachine.xml",
"informationModel_laserWeldingMachine.xml", "informationModel_laserWeldingMachine2.xml"};
private static final String[] pmmlFiles = {"AuditTree.xml", "IrisRandomForest.xml", "iristree_example.xml",
"single_audit_mlp.xml"};
public DatabaseInitializer(ModelRepository modelRepository, UserRepository userRepository,
ProjectRepository projectRepository, ModelFileRepository modelFileRepository,
DBFileRepository dbFileRepository, BusinessProcessRepository businessProcessRepository,
OrganisationUnitRepository organisationUnitRepository, EAMContainerRepository eamContainerRepository,
OpcuaInformationModelService opcuaInformationModelService,
OpcuaInformationModelRepository opcuaInformationModelRepository, ResourceLoader resourceLoader) {
this.modelRepository = modelRepository;
this.userRepository = userRepository;
this.projectRepository = projectRepository;
this.dbFileRepository = dbFileRepository;
this.modelFileRepository = modelFileRepository;
this.businessProcessRepository = businessProcessRepository;
this.organisationUnitRepository = organisationUnitRepository;
this.eamContainerRepository = eamContainerRepository;
this.opcuaInformationModelService = opcuaInformationModelService;
this.opcuaInformationModelRepository = opcuaInformationModelRepository;
this.resourceLoader = resourceLoader;
}
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
switch (activeProfile) {
case "production":
log.info("Application is running in production mode.");
break;
case "local":
log.info("Application is running non production mode.");
createDummyData();
break;
case "productionInit":
log.info("Application is running production init mode.");
createProductionData();
break;
default:
log.info("Application is running on a non knowing mode");
break;
}
}
private void createProductionData() {
createDummyData();
}
/**
* We do not need to clean the DB, it is create-drop by default
*/
private void createDummyData() {
List<User> users = createUsers();
List<Project> projects = createProjects(users);
userRepository.saveAll(users);
projectRepository.saveAll(projects);
List<Model> models = createForEachModelStatusModel(projects, users);
createEAMContainer(models);
createModelFile(models);
createOpcuaFile(models);
}
private List<User> createUsers() {
User user = DefaultDataBuilder.userBuilder.build();
User user1 = DefaultDataBuilder.userBuilder
.name("Alice")
.build();
User user2 = DefaultDataBuilder.userBuilder
.name("Jill")
.build();
return Arrays.asList(user, user1, user2);
}
private List<Project> createProjects(List<User> users) {
List<Project> projects = new ArrayList<>();
List<ProjectStatus> projectStatuses = Arrays.asList(ProjectStatus.values());
Collections.shuffle(projectDescriptionPrefixes);
for (int i = 0; i < projectUseCases.length; i++) {
LocalDate startDate = getRandomDate(LocalDate.now().minusYears(18L));
LocalDate creationDate = getRandomDate(startDate);
LocalDate endDate = getRandomDate(creationDate);
String description = "description for Enpro Project" + (i + 1);
if (i < projectDescriptionPrefixes.size()) {
description = projectDescriptionPrefixes.get(i) + " " + description;
}
Project project = DefaultDataBuilder.projetBuilder
.name(projectUseCases[i])
.useCase(projectUseCases[i])
.description(description)
.editors(Collections.singletonList(getRandomElement(users)))
.status(getRandomElement(projectStatuses))
.creationDate(creationDate)
.startDate(startDate)
.endDate(endDate)
.build();
projects.add(project);
}
return projects;
}
private List<Model> createForEachModelStatusModel(List<Project> projects, List<User> users) {
List<Model> models = new ArrayList<>();
List<ModelStatus> modelStatuses = Arrays.asList(ModelStatus.values());
projects.forEach(project -> {
int amountModelGroups = ThreadLocalRandom.current().nextInt(3, 8);
project.setModels(new ArrayList<>());
Collections.shuffle(modelNamePrefixes);
String modelBaseName = "Model for " + project.getUseCase();
for (int modelGroupIndex = 0; modelGroupIndex < amountModelGroups; modelGroupIndex++) {
String modelName = modelBaseName;
if (modelGroupIndex < modelNamePrefixes.size()) {
modelName = modelNamePrefixes.get(modelGroupIndex) + " " + modelBaseName;
}
String algorithm = getRandomElement(algorithmNames);
int amountModelsPerModelGroup = ThreadLocalRandom.current().nextInt(1, 10);
ModelGroup modelGroup = ModelGroup.builder()
.modelGroupName(modelName).build();
LocalDate dateOfCreation = getRandomDate(LocalDate.now().minusYears(18L));
LocalDate lastModified = getRandomDate(dateOfCreation);
for (long modelIndex = 1; modelIndex <= amountModelsPerModelGroup; modelIndex++) {
ModelMetadata modelMetadata = DefaultDataBuilder.getNewMetadataBuilder()
.name(modelName + modelIndex)
.author(getRandomElement(users))
.version(modelIndex)
.status(getRandomElement(modelStatuses))
.algorithm(algorithm)
.dateOfCreation(dateOfCreation)
.lastModified(lastModified)
.modelGroup(modelGroup)
.build();
Model model = DefaultDataBuilder.modelBuilder
.project(project)
.modelMetadata(modelMetadata)
.build();
if (ThreadLocalRandom.current().nextInt(5) == 0) {
model.setRelationalDBInformation(RelationalDBInformation.builder().url("http://enpro.de:8080")
.dbUser("testUser").password("password").type(DataSourceType.RELATIONAL_DATA_BASE)
.model(model).build());
}
modelRepository.save(model);
models.add(model);
dateOfCreation = getRandomDate(lastModified);
lastModified = getRandomDate(dateOfCreation);
}
}
});
return models;
}
private void createEAMContainer(List<Model> models) {
List<OrganisationUnit> organisationUnits = new ArrayList<>();
for (int i = 0; i < orgUnitNames.length; i++) {
organisationUnits.add(new OrganisationUnit(orgUnitNames[i], i));
}
List<BusinessProcess> businessProcesses = new ArrayList<>();
for (String businessProcessName : eamBusinessProcesses) {
if (CollectionUtils.isEmpty(businessProcesses)) {
businessProcesses.add(new BusinessProcess(null, businessProcessName));
} else {
businessProcesses.add(new BusinessProcess(
businessProcesses.get(businessProcesses.size() - 1), businessProcessName));
}
}
List<EAMContainer> eamContainers = new ArrayList<>();
models.stream()
.filter(model -> model.getModelMetadata().getStatus().equals(ModelStatus.OPERATION) ||
model.getModelMetadata().getStatus().equals(ModelStatus.PLANNED) ||
model.getModelMetadata().getStatus().equals(ModelStatus.MAINTENANCE))
.forEach(model -> {
EAMContainer eamContainer = EAMContainer.builder()
.businessProcess(getRandomElement(businessProcesses))
.organisationUnit(getRandomElement(organisationUnits))
.model(model).build();
eamContainers.add(eamContainer);
});
organisationUnitRepository.saveAll(organisationUnits);
businessProcessRepository.saveAll(businessProcesses);
eamContainerRepository.saveAll(eamContainers);
}
private void createModelFile(Iterable<Model> models) {
models.forEach(model -> {
if (model.getModelMetadata().getStatus() != ModelStatus.PLANNED) {
try {
ModelFile modelFile = new ModelFile();
DBFile dbFile = new DBFile();
String fileName = getRandomElement(Arrays.asList(pmmlFiles));
dbFile.setFileName(fileName);
dbFile.setFileType("text/xml");
dbFile.setData(ByteStreams.toByteArray(getmPmmlInputstream(fileName)));
modelFile.setFileSize(dbFile.getData().length);
List<Model> modelList = pmmlMetadataParser.parsePMMLFile(getmPmmlInputstream(fileName), model.getModelMetadata());
model.setModelMetadata(modelList.get(0).getModelMetadata());
modelFile.setDbFile(dbFile);
modelFile.setModel(model);
dbFileRepository.save(dbFile);
modelFileRepository.save(modelFile);
} catch (Exception e) {
log.info("Failed to load example pmml file, {}", e);
}
}
});
}
private void createOpcuaFile(List<Model> models) {
models.stream()
.filter(model -> model.getRelationalDBInformation() == null)
.forEach(model -> {
int n = ThreadLocalRandom.current().nextInt(4);
for (int i = 0; i < n; i++) {
OpcuaMetadata opcuaMetadata;
try {
String fileName = opcuaFiles[i];
DBFile dbFile = new DBFile();
dbFile.setFileName(fileName);
dbFile.setFileType("text/xml");
dbFile.setData(ByteStreams.toByteArray(getOpcuaInputstream(fileName)));
dbFile = dbFileRepository.save(dbFile);
opcuaMetadata = opcuaInformationModelService.parseOpcuaMetadata(getOpcuaInputstream(fileName), null, null);
OpcuaInformationModel opcuaInformationModel = new OpcuaInformationModel();
opcuaInformationModel.setDbFile(dbFile);
opcuaInformationModel.setOpcuaMetadata(opcuaMetadata);
opcuaInformationModel.setFileName(fileName);
opcuaInformationModel.setModel(model);
opcuaInformationModelRepository.save(opcuaInformationModel);
} catch (JAXBException | IOException e) {
log.info("Failed to parse opcua");
}
}
});
}
private <T> T getRandomElement(List<T> list) {
if (!list.isEmpty()) {
int index = ThreadLocalRandom.current().nextInt(list.size());
return list.get(index);
} else {
return null;
}
}
private InputStream getOpcuaInputstream(String fileName) {
try {
return resourceLoader.getResource("classpath:/example/opcua/" + fileName).getInputStream();
} catch (IOException e) {
log.info("Failed to load file: {}", e);
}
return null;
}
private InputStream getmPmmlInputstream(String fileName) {
try {
return resourceLoader.getResource("classpath:/example/pmml/" + fileName).getInputStream();
} catch (IOException e) {
log.info("Failed to load file: {}", e);
}
return null;
}
private LocalDate getRandomDate(LocalDate dateMin) {
int year = 365;
return dateMin.plusDays((long) ThreadLocalRandom.current().nextInt(2 * year));
}
}
| 47.924933 | 135 | 0.632356 |
368656f4636b5f203e4fbff1a0c41748619030e5 | 1,090 | package de.thecodelabs.storage.serializer;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* Class for saving and reading serialized data
*
* @author Deadlocker8
*/
public class Serializer
{
private Serializer()
{
}
/**
* Saves the given byte[] in to a file
*
* @param path String - savepath
* @param data byte[] - data to save
* @throws Exception
*/
public static void serializeToFile(String path, byte[] data) throws Exception
{
try(BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(path)))
{
stream.write(data);
}
}
/**
* Reads a byte[] from a file
*
* @param path String - savepath
* return byte[] - data
* @throws Exception
*/
public static byte[] deserializeFromFile(String path) throws Exception
{
byte[] buffer;
try(BufferedInputStream stream = new BufferedInputStream(new FileInputStream(path)))
{
buffer = new byte[stream.available()];
stream.read(buffer);
}
return buffer;
}
} | 20.566038 | 89 | 0.695413 |
aa2f272652f12e999ef50b73d34539905a594fc1 | 1,937 | package com.ruoyi.project.system.mapper;
import java.util.List;
import com.ruoyi.project.system.domain.SysPost;
import org.apache.ibatis.annotations.Param;
/**
* 岗位信息 数据层
*
* @author ruoyi
*/
public interface SysPostMapper
{
/**
* 查询岗位数据集合
*
* @param post 岗位信息
* @return 岗位数据集合
*/
public List<SysPost> selectPostList(SysPost post);
/**
* 查询所有岗位
*
* @return 岗位列表
*/
public List<SysPost> selectPostAll();
List<SysPost> selectPostAllByCom(@Param("comId")String comId);
/**
* 通过岗位ID查询岗位信息
*
* @param postId 岗位ID
* @return 角色对象信息
*/
public SysPost selectPostById(Long postId);
/**
* 根据用户ID获取岗位选择框列表
*
* @param userId 用户ID
* @return 选中岗位ID列表
*/
public List<Integer> selectPostListByUserId(Long userId);
/**
* 查询用户所属岗位组
*
* @param userName 用户名
* @return 结果
*/
public List<SysPost> selectPostsByUserName(String userName);
/**
* 删除岗位信息
*
* @param postId 岗位ID
* @return 结果
*/
public int deletePostById(@Param("postId") Long postId, @Param("comId") String comId);
/**
* 批量删除岗位信息
*
* @param postIds 需要删除的岗位ID
* @return 结果
*/
public int deletePostByIds(Long[] postIds);
/**
* 修改岗位信息
*
* @param post 岗位信息
* @return 结果
*/
public int updatePost(SysPost post);
/**
* 新增岗位信息
*
* @param post 岗位信息
* @return 结果
*/
public int insertPost(SysPost post);
/**
* 校验岗位名称
*
* @param postName 岗位名称
* @return 结果
*/
public SysPost checkPostNameUnique(@Param("postName") String postName, @Param("comId") String comId);
/**
* 校验岗位编码
*
* @param postCode 岗位编码
* @return 结果
*/
public SysPost checkPostCodeUnique( @Param("postCode") String postCode, @Param("comId") String comId);
}
| 18.805825 | 106 | 0.568921 |
ea32840ca067995562d0a4bcdf926e206fb3555f | 80 | package com.mao.lang;
public interface Obtainable {
public Object obtain();
}
| 13.333333 | 29 | 0.75 |
90f7f48ff9ca4f0dcbe15a943a64e70bd5fc05d6 | 9,508 | /*
* Copyright 1999-2017 Alibaba Group Holding 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 com.alibaba.druid.bvt.sql.oracle.create;
import com.alibaba.druid.sql.OracleTest;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.oracle.parser.OracleStatementParser;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleSchemaStatVisitor;
import com.alibaba.druid.util.JdbcConstants;
import org.junit.Assert;
import java.util.List;
public class OracleCreateTriggerTest6 extends OracleTest {
public void test_0() throws Exception {
String sql = //
"CREATE OR REPLACE TRIGGER XON_EPM.EPM_TG_FIRSTCHECK\n" +
"\tAFTER INSERT OR UPDATE\n" +
"\tON XON_EPM.EPM_TBL_FIRST_CERTIFICATION_AP\n" +
"\tFOR EACH ROW\n" +
"DECLARE\n" +
"\tvar_nContractID number;\n" +
"\tvar_dFirstCheckTime date;\n" +
"\tvar_nRecordCount number;\n" +
"\tvar_sState varchar2(16);\n" +
"BEGIN\n" +
"\tvar_sState := :NEW.State;\n" +
"\tvar_dFirstCheckTime := :NEW.Commiteddate;\n" +
"\tIF var_sState = 'approved' THEN\n" +
"\t\t-- 鏌ヨ\uE1D7鍚堝悓 ID\n" +
"\t\tSELECT etfca_.contractid\n" +
"\t\tINTO var_nContractID\n" +
"\t\tFROM XON_EPM.EPM_TBL_FIRST_CERTIFICATION etfc_, XON_EPM.EPM_TBL_FIRST_CHECK_APPLICATIO etfca_\n" +
"\t\tWHERE etfca_.oid = etfc_.applicationid\n" +
"\t\t\tAND etfc_.oid = :NEW.CERTIFICATIONID;\n" +
"\t\tIF var_nContractID > 0 THEN\n" +
"\t\t\t-- 鏌ヨ\uE1D7 EPM_TB_CONTRACT_EX 鏄\uE21A惁鏈夎\uE187褰�\n" +
"\t\t\tSELECT COUNT(*)\n" +
"\t\t\tINTO var_nRecordCount\n" +
"\t\t\tFROM XON_EPM.EPM_TB_CONTRACT_EX etce_\n" +
"\t\t\tWHERE etce_.ncontractid = var_nContractID;\n" +
"\t\t\tIF var_nRecordCount <= 0 THEN\n" +
"\t\t\t\tUPDATE XON_EPM.EPM_TBL_CONTRACT\n" +
"\t\t\t\tSET oid = oid\n" +
"\t\t\t\tWHERE XON_EPM.EPM_TBL_CONTRACT.OID = var_nContractID;\n" +
"\t\t\tEND IF;\n" +
"\t\t\tUPDATE XON_EPM.EPM_TB_CONTRACT_EX\n" +
"\t\t\tSET dFirstCheckTime = var_dFirstCheckTime\n" +
"\t\t\tWHERE XON_EPM.EPM_TB_CONTRACT_EX.NCONTRACTID = var_nContractID;\n" +
"\t\tEND IF;\n" +
"\tEND IF;\n" +
"END;";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
Assert.assertEquals(1, statementList.size());
Assert.assertEquals("CREATE OR REPLACE TRIGGER XON_EPM.EPM_TG_FIRSTCHECK\n" +
"\tAFTER INSERT OR UPDATE\n" +
"\tON XON_EPM.EPM_TBL_FIRST_CERTIFICATION_AP\n" +
"\tFOR EACH ROW\n" +
"DECLARE\n" +
"\tvar_nContractID number;\n" +
"\tvar_dFirstCheckTime date;\n" +
"\tvar_nRecordCount number;\n" +
"\tvar_sState varchar2(16);\n" +
"BEGIN\n" +
"\tvar_sState := :NEW.State;\n" +
"\tvar_dFirstCheckTime := :NEW.Commiteddate;\n" +
"\tIF var_sState = 'approved' THEN\n" +
"\t\t-- 鏌ヨ\uE1D7鍚堝悓 ID\n" +
"\t\tSELECT etfca_.contractid\n" +
"\t\tINTO var_nContractID\n" +
"\t\tFROM XON_EPM.EPM_TBL_FIRST_CERTIFICATION etfc_, XON_EPM.EPM_TBL_FIRST_CHECK_APPLICATIO etfca_\n" +
"\t\tWHERE etfca_.oid = etfc_.applicationid\n" +
"\t\t\tAND etfc_.oid = :NEW.CERTIFICATIONID;\n" +
"\t\tIF var_nContractID > 0 THEN\n" +
"\t\t\t-- 鏌ヨ\uE1D7 EPM_TB_CONTRACT_EX 鏄\uE21A惁鏈夎\uE187褰�\n" +
"\t\t\tSELECT COUNT(*)\n" +
"\t\t\tINTO var_nRecordCount\n" +
"\t\t\tFROM XON_EPM.EPM_TB_CONTRACT_EX etce_\n" +
"\t\t\tWHERE etce_.ncontractid = var_nContractID;\n" +
"\t\t\tIF var_nRecordCount <= 0 THEN\n" +
"\t\t\t\tUPDATE XON_EPM.EPM_TBL_CONTRACT\n" +
"\t\t\t\tSET oid = oid\n" +
"\t\t\t\tWHERE XON_EPM.EPM_TBL_CONTRACT.OID = var_nContractID;\n" +
"\t\t\tEND IF;\n" +
"\t\t\tUPDATE XON_EPM.EPM_TB_CONTRACT_EX\n" +
"\t\t\tSET dFirstCheckTime = var_dFirstCheckTime\n" +
"\t\t\tWHERE XON_EPM.EPM_TB_CONTRACT_EX.NCONTRACTID = var_nContractID;\n" +
"\t\tEND IF;\n" +
"\tEND IF;\n" +
"END;",//
SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE));
Assert.assertEquals("CREATE OR REPLACE TRIGGER XON_EPM.EPM_TG_FIRSTCHECK\n" +
"\tAFTER INSERT OR UPDATE\n" +
"\tON XON_EPM.EPM_TBL_FIRST_CERTIFICATION_AP\n" +
"\tFOR EACH ROW\n" +
"DECLARE\n" +
"\tvar_nContractID number;\n" +
"\tvar_dFirstCheckTime date;\n" +
"\tvar_nRecordCount number;\n" +
"\tvar_sState varchar2(16);\n" +
"BEGIN\n" +
"\tSET var_sState := :NEW.State;\n" +
"\tSET var_dFirstCheckTime := :NEW.Commiteddate;\n" +
"\tIF var_sState = 'approved' THEN\n" +
"\t\t-- 鏌ヨ\uE1D7鍚堝悓 ID\n" +
"\t\tSELECT etfca_.contractid\n" +
"\t\tINTO var_nContractID\n" +
"\t\tFROM XON_EPM.EPM_TBL_FIRST_CERTIFICATION etfc_, XON_EPM.EPM_TBL_FIRST_CHECK_APPLICATIO etfca_\n" +
"\t\tWHERE etfca_.oid = etfc_.applicationid\n" +
"\t\t\tAND etfc_.oid = :NEW.CERTIFICATIONID;\n" +
"\t\tIF var_nContractID > 0 THEN\n" +
"\t\t\t-- 鏌ヨ\uE1D7 EPM_TB_CONTRACT_EX 鏄\uE21A惁鏈夎\uE187褰�\n" +
"\t\t\tSELECT COUNT(*)\n" +
"\t\t\tINTO var_nRecordCount\n" +
"\t\t\tFROM XON_EPM.EPM_TB_CONTRACT_EX etce_\n" +
"\t\t\tWHERE etce_.ncontractid = var_nContractID;\n" +
"\t\t\tIF var_nRecordCount <= 0 THEN\n" +
"\t\t\t\tUPDATE XON_EPM.EPM_TBL_CONTRACT\n" +
"\t\t\t\tSET oid = oid\n" +
"\t\t\t\tWHERE XON_EPM.EPM_TBL_CONTRACT.OID = var_nContractID;\n" +
"\t\t\tEND IF;\n" +
"\t\t\tUPDATE XON_EPM.EPM_TB_CONTRACT_EX\n" +
"\t\t\tSET dFirstCheckTime = var_dFirstCheckTime\n" +
"\t\t\tWHERE XON_EPM.EPM_TB_CONTRACT_EX.NCONTRACTID = var_nContractID;\n" +
"\t\tEND IF;\n" +
"\tEND IF;\n" +
"END;",//
SQLUtils.toSQLString(stmt, JdbcConstants.POSTGRESQL));
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
Assert.assertEquals(1, visitor.getTables().size());
// Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("cdc.en_complaint_ipr_stat_fdt0")));
Assert.assertEquals(0, visitor.getColumns().size());
// Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "*")));
// Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR")));
// Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode")));
}
}
| 55.27907 | 127 | 0.517775 |
61b3e75eaa8096fced63fddc20091fa3d8b4061d | 468 | package com.devskiller.jfairy.producer.person.locale.zh;
import org.apache.commons.lang3.RandomStringUtils;
import com.devskiller.jfairy.producer.person.PassportNumberProvider;
/**
* com.devskiller.jfairy.producer.person.locale.zh.ZhPassportNumberProvider
*
* @author lhfcws
* @since 2017/3/2
*/
public class ZhPassportNumberProvider implements PassportNumberProvider {
@Override
public String get() {
return RandomStringUtils.randomAlphanumeric(9);
}
}
| 23.4 | 75 | 0.797009 |
b7fd851b1d85a4629c5fddb7cdda92bde080796a | 1,498 | package co.shubhamgupta.vogue.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import co.shubhamgupta.vogue.model.Product;
import co.shubhamgupta.vogue.repository.ProductRepository;
@Service
public class ProductService {
private final ProductRepository repository;
@Autowired
public ProductService(ProductRepository repository) {
this.repository = repository;
}
public List<Product> getProducts() {
return repository.findAll();
}
public List<Product> getProductsSortedByGender(Character gender) {
if(gender == 'M')
return repository.findAllByOrderByGenderAsc();
else
return repository.findAllByOrderByGenderDesc();
}
public List<Product> getProductsSortedByNewArrival() {
return repository.findAllByOrderByIsNewArrivalDesc();
}
public List<Product> getProductsSortedByDiscount() {
return repository.findAllByOrderByDiscountDesc();
}
public List<Product> getProductsFilteredByGender(Character gender) {
return repository.findAllByGender(gender);
}
public List<Product> getProductsFilteredByNewArrival() {
return repository.findAllByIsNewArrival();
}
public List<Product> getProductsFilteredByDiscount() {
return repository.findAllByDiscount();
}
public List<Product> getProductsFilteredBySearchKeyword(String keyword) {
return repository.search(keyword);
}
public Product getProductById(long id) {
return repository.getById(id);
}
}
| 24.966667 | 74 | 0.790387 |
4b12a48263a5508b8171c66e2db28b6cc45aea3d | 10,126 | package com.joyfulmagic.colors.databases.UserDatabase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.joyfulmagic.colors.databases.ColorDatabase.ColorDatabase;
import com.joyfulmagic.colors.databases.ColorDatabase.ColorString;
import com.joyfulmagic.colors.utils.Timer;
/**
* User database for saving progress of user
*/
public class UserDatabase extends SQLiteOpenHelper {
// Database
private static final String DATABASE_NAME = "users.db";
private static final int DATABASE_VERSION = 1;
// Table USERS
private static final String TABLE_NAME_USERS = "USERS";
private static final String COLUMN_NAME_NAME_USER = "NAME";
private static final String USERS_CREATE_TABLE_QUERY =
"create table " + TABLE_NAME_USERS +" ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME_NAME_USER +" TEXT" + ");";
// Table of USERNAME
public static final String[] COLUMN_NAME_NAMES_COLORS = ColorDatabase.COLUMN_NAME_NAMES_COLORS;
public static final String COLUMN_NAME_CODE_HEX = ColorDatabase.COLUMN_NAME_CODE_HEX;
public static final String COLUMN_NAME_STATUS_LEARN = "STATUS_LEARN";
public static final String COLUMN_NAME_NUMBER_SHOWS = "NUMBER_SHOWS";
public static final String COLUMN_NAME_NUMBER_ANSWERS = "NUMBER_ANSWERS";
public static final String COLUMN_NAME_DATE_SHOW = "DATE_SHOW";
// creation of table query getter
private String getUsernameCreateTableQuery(String userName){
return "create table " + userName + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME_NAMES_COLORS[0] +" TEXT,"
+ COLUMN_NAME_NAMES_COLORS[1] +" TEXT,"
+ COLUMN_NAME_CODE_HEX +" TEXT,"
+ COLUMN_NAME_STATUS_LEARN + " BOOLEAN,"
+ COLUMN_NAME_NUMBER_SHOWS + " INTEGER,"
+ COLUMN_NAME_NUMBER_ANSWERS + " INTEGER,"
+ COLUMN_NAME_DATE_SHOW + " TIMESTAMP" + ");";
}
// app context
private Context context;
// Constructor
public UserDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USERS_CREATE_TABLE_QUERY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
/**
* Add new user to database
* @param userName name of user
*/
public void writeNewUser(String userName){
SQLiteDatabase db = this.getWritableDatabase();
// insert new user in table USERS
ContentValues newUser = new ContentValues();
newUser.put(COLUMN_NAME_NAME_USER, userName);
db.insert(TABLE_NAME_USERS, null, newUser);
// making new table for USERNAME
db.execSQL(getUsernameCreateTableQuery(userName));
}
/**
* Check for user exist
* @param userName name of user
* @return yes or no
*/
public boolean userNameExist(String userName){
boolean result = false;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_NAME_USERS, new String[]{COLUMN_NAME_NAME_USER}, null, null, null, null, null);
if(c != null) {
if(c.getCount() > 0) {
c.moveToFirst();
boolean exitFlag = false;
while (exitFlag != true) {
String userNameFromTable = c.getString(c.getColumnIndex(COLUMN_NAME_NAME_USER));
if (userNameFromTable.equals(userName)) {
result = true;
break;
}
exitFlag = !c.moveToNext();
}
}
}
return result;
}
/**
* Get all colors which user is should to learn
* @param userName name of user
* @return cursor with colors
*/
public Cursor getUserLearnColors(String userName){
Cursor c = null;
SQLiteDatabase db = this.getReadableDatabase();
try{
c = db.query(userName, null,
COLUMN_NAME_STATUS_LEARN + " != ?",
new String[]{"false"},
null, null, "random()");
// hm, there is no function RAND(), try random() what if in different versions this function absent
c.moveToFirst();
}
catch (IllegalStateException e){
e.printStackTrace();
}
return c;
}
/**
* All users color getter
* @param userName name of dude
* @return colors
*/
public Cursor getUserAllColors(String userName){
Cursor c = null;
SQLiteDatabase db = this.getReadableDatabase();
try{
c = db.query(userName, null,
null,
null,
null, null, null);
// hm, there is no function RAND(), try random() what if in different versions this function absent
c.moveToFirst();
}
catch (IllegalStateException e){
e.printStackTrace();
}
return c;
}
// return cursor of color from user name and hex code
public Cursor getColorByHex(String userName, String hex){
Cursor c = null;
SQLiteDatabase db = this.getReadableDatabase();
try {
c = db.query(userName, null,
COLUMN_NAME_CODE_HEX + " = ?",
new String[]{hex},
null, null, null);
c.moveToFirst();
} catch (IllegalStateException e){
e.printStackTrace();
}
return c;
}
/**
* Load new color set for learning to user table
* @param userName name of man
* @param colorSet set of color
*/
public void loadNewColorSet(String userName, Cursor colorSet){
SQLiteDatabase db = this.getWritableDatabase();
boolean stopFlag = colorSet.moveToFirst();
while(stopFlag != false){
ColorString colorString = new ColorString(colorSet);
db.insert(userName, null, makeNewColorContentValue(colorString));
// next color
stopFlag = colorSet.moveToNext();
}
}
/**
* Make content value from color string
* @param colorString color name + hex
* @return content value
*/
public ContentValues makeNewColorContentValue(ColorString colorString){
ContentValues newColor = new ContentValues();
newColor.put(COLUMN_NAME_NAMES_COLORS[0], colorString.names[0]);
newColor.put(COLUMN_NAME_NAMES_COLORS[1], colorString.names[1]);
newColor.put(COLUMN_NAME_CODE_HEX, colorString.hex);
newColor.put(COLUMN_NAME_STATUS_LEARN, "true");
newColor.put(COLUMN_NAME_NUMBER_SHOWS, String.valueOf(0));
newColor.put(COLUMN_NAME_NUMBER_ANSWERS, String.valueOf(0));
newColor.put(COLUMN_NAME_DATE_SHOW, Timer.getTime().toString());
return newColor;
}
/**
* Load color string to to DB
* @param userName name of user
* @param colorString string of color
*/
public void loadColorString(String userName,ColorString colorString){
SQLiteDatabase db = this.getWritableDatabase();
db.insert(userName, null, makeNewColorContentValue(colorString));
}
/**
* Update color in DB by color card
* @param userName name of man
* @param color color card
*/
public void updateColor(String userName, ColorCard color){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues updateFields = new ContentValues();
updateFields.put(COLUMN_NAME_STATUS_LEARN, String.valueOf(color.status_learn));
updateFields.put(COLUMN_NAME_NUMBER_SHOWS, String.valueOf(color.shows));
updateFields.put(COLUMN_NAME_NUMBER_ANSWERS, String.valueOf(color.answers));
updateFields.put(COLUMN_NAME_DATE_SHOW, String.valueOf(color.date));
String selectString = COLUMN_NAME_CODE_HEX + " =?";
db.update(
userName,
updateFields,
selectString,
new String[]{color.bad_hex}
);
}
/**
* Column is there?
* @param userName name of lamer
* @param columnName name of column
* @return true or false
*/
boolean checkNameRight(String userName, String columnName){
SQLiteDatabase db = this.getWritableDatabase();
try{
Cursor c = db.rawQuery(
"SELECT * FROM " + userName
+ " WHERE " + columnName
+ " IS NULL OR " + columnName
+ "='';", null);
c.moveToFirst();
if (c.getCount() > 0) {
// System.out.println("UD: need to be updated..");
return false;
}
else {
// System.out.println("UD: alll right..");
}
} catch (Exception e){
e.printStackTrace();
}
return true;
}
// the same fun up here
boolean checkColumnExist(String userName, String columnName){
SQLiteDatabase db = this.getWritableDatabase();
try{
Cursor c = db.rawQuery("SELECT * FROM " + userName + " LIMIT 0;", null);
if (c.getColumnIndex(columnName) != -1)
return true;
} catch (Exception e){
e.printStackTrace();
}
return false;
}
// !
public void deleteUsersDatabase(){
if(context != null)
context.deleteDatabase(DATABASE_NAME);
// isn't work correctly
// TODO make delete fun
}
} | 31.349845 | 113 | 0.589769 |
3fa9fceb548ac458f4a7ebc752655a273b3bb581 | 9,512 | package com.seras.api;
import com.seras.constants.LogConstants;
import com.seras.enums.SpreadSheetFormat;
import com.seras.exceptions.InvalidSpreadSheetFormatException;
import com.seras.interfaces.ExcelParserHSSF;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.logging.Logger;
public class ExcelParserHSSFCore implements ExcelParserHSSF {
/* begin singleton */
private static ExcelParserHSSFCore excelParserHSSFCore;
private ExcelParserHSSFCore(){}
public static ExcelParserHSSFCore getInstance(){
if (excelParserHSSFCore==null)
excelParserHSSFCore=new ExcelParserHSSFCore();
rowPointer=0;
isFirstRowCellHeader=false;
sheetPointer=0;
return excelParserHSSFCore;
}
/* end singleton */
private static int rowPointer =0;
private static boolean isFirstRowCellHeader=false;
private static int sheetPointer =0;
Logger logger = Logger.getLogger(ExcelParserHSSFCore.class.getName());
@Override
public HSSFWorkbook getHssfWorkbookFromFile(File file) throws InvalidSpreadSheetFormatException, IOException {
SpreadSheetFormat spreadSheetFormat;
try {
spreadSheetFormat = ExcelUtilCore.getInstance().findXmlSpreadSheetFormat(file);
} catch (Exception e){e.printStackTrace(); return null; }
if (!spreadSheetFormat.equals(SpreadSheetFormat.HSSF)){
throw new InvalidSpreadSheetFormatException("Given file format is not HSSF format!");
}
FileInputStream fileInputStream = new FileInputStream(file);
return new HSSFWorkbook(fileInputStream);
}
@Override
public List<HSSFSheet> getHssfSheetsFromFile(File file) throws IOException, InvalidSpreadSheetFormatException {
List<HSSFSheet> sheets= new ArrayList<>();
HSSFWorkbook workbook = getHssfWorkbookFromFile(file);
int counterOfSheets = workbook.getNumberOfSheets();
if (counterOfSheets<=0){ return null; }
for (int i =0; i<counterOfSheets;i++){
sheets.add(workbook.getSheetAt(i));
}
return sheets;
}
@Override
public HSSFSheet getHssfSheetFromFileByIndex(File file, int index) throws IOException, InvalidSpreadSheetFormatException {
HSSFWorkbook workbook = getHssfWorkbookFromFile(file);
if(index> workbook.getNumberOfSheets()){return null;}
return workbook.getSheetAt(index);
}
@Override
public HSSFSheet getHssfSheetFromFileByName(File file, String sheet) throws IOException, InvalidSpreadSheetFormatException {
HSSFWorkbook workbook =getHssfWorkbookFromFile(file);
return workbook.getSheet(sheet);
}
@Override
public List<HSSFRow> getHssfRowsBySheet(HSSFSheet sheet) {
List<HSSFRow> rows =new ArrayList<>();
Iterator<Row> rowIterator =sheet.rowIterator();
while (rowIterator.hasNext()){
rows.add((HSSFRow) rowIterator.next());
}
return rows;
}
@Override
public HSSFRow getHssfRowBySheetAndIndex(HSSFSheet sheet, int index) {
if (sheet==null)
return null;
return sheet.getRow(index);
}
@Override
public List<HSSFCell> getHssfCellsByRow(HSSFRow row) {
if (row==null)return null;
List<HSSFCell> cells=new ArrayList<>();
Iterator<Cell> cellIterator=row.cellIterator();
while (cellIterator.hasNext()){
cells.add((HSSFCell) cellIterator.next());
}
return cells;
}
@Override
public HSSFCell getHssfCellByRowAndIndex(HSSFRow row, int index) {
if (row==null)return null;
if (index>row.getPhysicalNumberOfCells())return null;
return row.getCell(index);
}
@Override
public List<Map<String, String>> parseHssfSheetToMapList(HSSFSheet sheet) {
if (sheet==null)
return null;
List<Map<String,String>> rowListAsMap=new ArrayList<>();
List<HSSFRow> hssfRowList = getHssfRowsBySheet(sheet);
if (Optional.ofNullable(hssfRowList).map(List::size).orElse(0).equals(0)) {
logger.warning(LogConstants.getInstance().msgRowListEmpty);
return null;
}
logger.info("Start parsing rows to map...");
for (int i =0;i<hssfRowList.size();i++){
if (i<rowPointer)
continue;
Map<String,String> rowMap = parseHssfRowToMap(hssfRowList.get(i));
rowListAsMap.add(rowMap);
}
// hssfRowList.forEach(s->{
// Map<String,String> rowMap = parseHssfRowToMap(s);
// rowListAsMap.add(rowMap);
// });
return rowListAsMap;
}
@Override
public Map<String, String> parseHssfRowToMap(HSSFRow row) {
if (row==null)
{
logger.warning(LogConstants.getInstance().msgRowEmpty);
return null;
}
Map<String,String> map = new HashMap<>();
List<String> headerList ;
if(isFirstRowCellHeader){
headerList = findCellHeaderNamesFromFirstRowHssfRowByRow(row);
}else{
headerList =findCellHeaderNamesByFirstHssfRowDefault(row);
}
if(headerList==null)
{
logger.warning(LogConstants.getInstance().msgHeaderListEmpty);
return null;
}
logger.info(String.format("Header List ->%s",String.join(",", headerList)));
for (int i =0;i<headerList.size();i++){
HSSFCell cell= row.getCell(i);
String cellValueAsString = cell ==null ? "":cell.toString();
map.put(headerList.get(i),cellValueAsString);
}
List<String> mapLogList =new ArrayList<>();
map.forEach((s,v)-> mapLogList.add(String.format("\n Cell Header : %s,Value : %s",s,v)));
logger.info(String.format("Row Parsed To Map. %s",String.join(",",mapLogList)));
return map;
}
@Override
public List<Map<String, String>> parseHssfWorkBookToMapList(HSSFWorkbook workbook) {
if(workbook ==null){
logger.warning(LogConstants.getInstance().msgWorkbookEmpty);
return null;
}
HSSFSheet sheet = workbook.getSheetAt(sheetPointer);
return parseHssfSheetToMapList(sheet);
}
@Override
public List<Map<String, String>> parseHssfFileToMapList(File file) throws IOException, InvalidSpreadSheetFormatException {
if(file ==null){
logger.warning(LogConstants.getInstance().msgFileEmpty);
return null;
}
HSSFWorkbook workbook = getHssfWorkbookFromFile(file);
return parseHssfWorkBookToMapList(workbook);
}
@Override
public List<String>findCellHeaderNamesFromFirstRowHssfRowByRow(HSSFRow row) {
if (row==null) return null;
HSSFRow targetRow;
int cellCountOfTargetRow;
List<String> headerList=new ArrayList<>();
targetRow=row.getSheet().getRow(rowPointer);
if (targetRow==null) return null;
cellCountOfTargetRow =targetRow.getLastCellNum();
logger.info(String.format("Searching Hssf cell header by row. Start row ->%s",rowPointer));
for (int i =0;i<cellCountOfTargetRow;i++){
headerList.add(targetRow.getCell(i).toString());
}
logger.info(String.format("Document headers -> %s", String.join(",", headerList)));
return headerList;
}
@Override
public List<String> findCellHeaderNamesByFirstHssfRowDefault(HSSFRow row) {
if (row==null)
return null;
List<String> headerList =new ArrayList<>();
int firstRowCellNumber ;
firstRowCellNumber= Optional.of(row).map(Row::getSheet).map(s->s.getRow(rowPointer)).map(Row::getLastCellNum).orElse(new Short("0"));
// firstRowCellNumber=row.getSheet().getRow(rowPointer).getLastCellNum();
for (int i =0;i<firstRowCellNumber;i++){
headerList.add(CellReference.convertNumToColString(i));
}
return headerList;
}
@Override
public Integer getMaxRowCount(HSSFSheet sheet) {
if(sheet ==null){
return -1;
}
return sheet.getPhysicalNumberOfRows();
}
@Override
public List<String> getSheetNames(HSSFWorkbook workbook) {
List<String> nameList = new ArrayList<String>();
if(workbook==null){
return null;
}
int sheetCount=workbook.getNumberOfSheets();
for (int i =0; i<sheetCount;i++){
nameList.add(workbook.getSheetName(i));
}
return nameList;
}
public ExcelParserHSSFCore setRowPointer(int startPointer){
ExcelParserHSSFCore.rowPointer =startPointer;
return this;
}
public ExcelParserHSSFCore setIsFirstRowCellHeader(boolean isFirstRowCellHeader){
ExcelParserHSSFCore.isFirstRowCellHeader = isFirstRowCellHeader;
return this;
}
public ExcelParserHSSFCore setSheetPointer(int sheetPointer){
ExcelParserHSSFCore.sheetPointer=sheetPointer;
return this;
}
}
| 31.496689 | 144 | 0.655067 |
16112d1b86d96b593fede03ffe8053b7218bcdff | 414 | package xyz.rensaa.providerservice.repository;
import org.springframework.data.repository.CrudRepository;
import xyz.rensaa.providerservice.model.Treatments.TreatmentLicenseAssignment;
import java.util.List;
public interface TreatmentLicenseAssignmentRepository extends CrudRepository<TreatmentLicenseAssignment, String> {
List<TreatmentLicenseAssignment> findAllByLicenseAddress(String licenseAddress);
}
| 37.636364 | 115 | 0.86715 |
8595c94d340e587b8b0086e3b02d91c6d1bf641a | 1,818 | /**
* 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.hadoop.hdfs.server.datanode;
/**
* WARNING!! This is TEST ONLY class: it never has to be used
* for ANY development purposes.
*
* This is a utility class to expose DataNode functionality for
* unit and functional tests.
*/
public class DataNodeAdapter {
/**
* Fetch a copy of ReplicaInfo from a datanode by block id
* @param dn datanode to retrieve a replicainfo object from
* @param bpid Block pool Id
* @param blkId id of the replica's block
* @return copy of ReplicaInfo object @link{FSDataset#fetchReplicaInfo}
*/
public static ReplicaInfo fetchReplicaInfo (final DataNode dn,
final String bpid,
final long blkId) {
return ((FSDataset)dn.data).fetchReplicaInfo(bpid, blkId);
}
public static void setHeartbeatsDisabledForTests(DataNode dn,
boolean heartbeatsDisabledForTests) {
dn.setHeartbeatsDisabledForTests(heartbeatsDisabledForTests);
}
}
| 39.521739 | 75 | 0.709021 |
12c3c9cce2ab50499698a8ef5f39dbfbd80f9471 | 949 | package calcu;
public class Class_ohmLaw2 {
private double resis;
private double resMa;
private double comp;
private double areaTra;
public double getResis() {
return resis;
}
public void setResis(double resis) {
this.resis = resis;
}
public double getResMa() {
return resMa;
}
public void setResMa(double resMa) {
this.resMa = resMa;
}
public double getComp() {
return comp;
}
public void setComp(double comp) {
this.comp = comp;
}
public double getAreaTra() {
return areaTra;
}
public void setAreaTra(double areaTra) {
this.areaTra = areaTra;
}
public Class_ohmLaw2(){
resis = 0.0;
resMa = 0.0;
comp = 0.0;
areaTra = 0.0;
}
public double ohmLaw2(){
resis = (resMa * comp) / areaTra;
return resis;
}
}
| 16.946429 | 44 | 0.537408 |
1e2136014cf7a9a4bb59ad12d870d8f1e79338f0 | 737 | import java.net.Socket;
import java.io.PrintWriter;
import java.io.IOException;
public class SimpleJavaSocketClient {
public static void main(String[] args) throws Exception {
System.out.println("Sending Message to Client :)"); // System Output
try {
Socket socket = new Socket("192.168.0.17", 1234); // IP Address, Port
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
printWriter.write("This is the sample message sent from Kyle's Server"); // Message to send
printWriter.flush();
printWriter.close();
socket.close();
} catch (IOException e) {
e.printStackTrace(); // Print Error
}
}
}
| 30.708333 | 103 | 0.618725 |
83ba6c0c14762b1013d5b7c6773384c8ca0b4504 | 7,061 | package com.st.novatech.springlms.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.st.novatech.springlms.exception.TransactionException;
import com.st.novatech.springlms.model.Book;
import com.st.novatech.springlms.model.Borrower;
import com.st.novatech.springlms.model.Branch;
import com.st.novatech.springlms.model.Loan;
/**
* Tests of the administrator service class.
* @author Salem Ozaki
* @author Jonathan Lovelace (integration and polishing)
*/
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class SalemAdministratorServiceTest {
/**
* Sample book title used in tests.
*/
private static final String SAMPLE_TITLE = "The Book Title";
/**
* Sample branch name used in tests.
*/
private static final String SAMPLE_BRANCH_NAME = "The Branch Name";
/**
* Sample branch address used in tests.
*/
private static final String SAMPLE_BRANCH_ADDRESS = "601 New Jersey Ave, Washington, DC 20001";
/**
* Sample borrower name used in tests.
*/
private static final String SAMPLE_PATRON_NAME = "The Borrower Name";
/**
* Sample borrower address used in tests.
*/
private static final String SAMPLE_PATRON_ADDRESS = "650 New Jersey Ave, Washington, DC 20001";
/**
* Sample borrower phone used in tests.
*/
private static final String SAMPLE_PATRON_PHONE = "1234567890";
/**
* Due date for testing purposes, two weeks from today.
*/
private static final LocalDate OFFICIAL_DUE_DATE = LocalDate.now().plusWeeks(2);
/**
* Number of copies for testing purposes.
*/
private static final int NUM_COPIES = 50;
/**
* Stored borrower from tests.
*
* <p>(TODO: Is this ever read without being first written to in the same test?)
*/
private Borrower testBorrower;
/**
* Stored book from tests.
*
* <p>(TODO: Is this ever read without being first written to in the same test?)
*/
private Book testBook;
/**
* Stored loan from tests.
*
* <p>(TODO: Is this ever read without being first written to in the same test?)
*/
private Loan testLoan;
/**
* Stored branch from tests.
*
* <p>(TODO: Is this ever read without being first written to in the same test?)
*/
private Branch testBranch;
/**
* Administrator service object under test.
*/
@Autowired
private AdministratorService adminService;
/**
* Borrower service object involved in tests.
*/
@Autowired
private BorrowerService borrowerService;
/**
* Librarian service object involved in tests.
*/
@Autowired
private LibrarianService libraryService;
/**
* Set up the database connection, service objects, and test data for each test.
*
* @throws SQLException on database errors
* @throws IOException on I/O error reading database schema from file
* @throws TransactionException on error caught by the service layer
*/
@BeforeEach
public void init() throws SQLException, TransactionException, IOException {
testBorrower = adminService.createBorrower(SAMPLE_PATRON_NAME, SAMPLE_PATRON_ADDRESS,
SAMPLE_PATRON_PHONE);
testBook = adminService.createBook(SAMPLE_TITLE, null, null);
testBranch = adminService.createBranch(SAMPLE_BRANCH_NAME, SAMPLE_BRANCH_ADDRESS);
libraryService.setBranchCopies(testBranch, testBook, NUM_COPIES);
testLoan = borrowerService.borrowBook(testBorrower, testBook, testBranch,
LocalDateTime.now(), OFFICIAL_DUE_DATE);
}
/**
* Clean up after each test.
* @throws SQLException on database error
* @throws TransactionException on error caught by the service layer
*/
@AfterEach
public void tearThis() throws SQLException, TransactionException {
borrowerService.returnBook(testBorrower, testBook, testBranch,
LocalDate.now());
libraryService.setBranchCopies(testBranch, testBook, 0);
adminService.deleteBorrower(testBorrower);
adminService.deleteBook(testBook);
adminService.deleteBranch(testBranch);
}
/**
* Test that overriding due dates works.
* @throws SQLException on error in DAO or below
* @throws TransactionException on error caught by service class
*/
@DisplayName("Override due date correctly")
@Test
public void overrideDueDateForLoanTest()
throws SQLException, TransactionException {
final boolean success = adminService.overrideDueDateForLoan(testBook,
testBorrower, testBranch, OFFICIAL_DUE_DATE.plusWeeks(1));
final List<Loan> listOfLoansWithOneLoan = getListThatMatches(testBook,
testBorrower, testBranch);
assertEquals(1, listOfLoansWithOneLoan.size(), "only one lon");
final Loan foundLoan = listOfLoansWithOneLoan.get(0);
assertTrue(success, "override operation reported success");
assertEquals(testLoan.getDueDate().plusWeeks(1), foundLoan.getDueDate(),
"new due date is as expected");
}
/**
* Test that overriding due dates fails if no such loan exists.
* @throws SQLException on error in DAO or below
* @throws TransactionException on error caught by service class
*/
@DisplayName("Override due date fails because there is no such loan")
@Test
public void overrideDueDateForNullLoanTest()
throws SQLException, TransactionException {
final Book nonExistingBook = new Book(Integer.MAX_VALUE, "Some Title", null,
null);
final boolean success = adminService.overrideDueDateForLoan(nonExistingBook,
testBorrower, testBranch, OFFICIAL_DUE_DATE.plusWeeks(1));
final List<Loan> listOfLoansWithNoLoan = getListThatMatches(nonExistingBook,
testBorrower, testBranch);
assertEquals(0, listOfLoansWithNoLoan.size(), "no matching loans when loan does not exist");
final List<Loan> listOfLoansWithOneLoan = getListThatMatches(testBook,
testBorrower, testBranch);
assertEquals(1, listOfLoansWithOneLoan.size(), "only one matching loan");
final Loan foundLoan = listOfLoansWithOneLoan.get(0);
assertFalse(success, "override operation reported failure");
assertEquals(testLoan.getDueDate(), foundLoan.getDueDate(), "due date didn't change");
}
private List<Loan> getListThatMatches(final Book book, final Borrower borrower,
final Branch branch) throws TransactionException {
final List<Loan> tempListOfAllLoans = adminService.getAllLoans();
return tempListOfAllLoans
.parallelStream()
.filter(l -> l.getBook().equals(book)
&& l.getBorrower().equals(borrower)
&& l.getBranch().equals(branch))
.collect(Collectors.toList());
}
}
| 32.995327 | 96 | 0.756975 |
7c832374cc47484a47ca4af6c338161e7a606136 | 156 | package g_earth.protocol.hostreplacer;
public interface HostReplacer {
void addRedirect(String[] lines);
void removeRedirect(String[] lines);
}
| 15.6 | 40 | 0.74359 |
a73fbfd2f3897abc2d58a7aa690dc6eb0169a35e | 182 | package sif3.au.naplan.provider.service;
import sif.dd.au30.model.SchoolInfoCollectionType;
public interface SchoolInfoService extends NaplanService<SchoolInfoCollectionType> {
}
| 22.75 | 84 | 0.846154 |
ac3a61da3d9930c494875968b896b6d1d21925d7 | 58 | package nfl.playdb.dao;
public interface TackleDAO {
}
| 8.285714 | 28 | 0.741379 |
0780275d24a06575f55fc02cf9729956f9683637 | 1,505 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.atalk.impl.androidupdate;
import net.java.sip.communicator.service.update.UpdateService;
import net.java.sip.communicator.util.ServiceUtils;
import net.java.sip.communicator.util.SimpleServiceActivator;
import org.atalk.service.configuration.ConfigurationService;
import org.osgi.framework.BundleContext;
/**
* Android update service activator.
*
* @author Pawel Domas
*/
public class UpdateActivator extends SimpleServiceActivator<UpdateService> {
/**
* <tt>BundleContext</tt> instance.
*/
static BundleContext bundleContext;
/**
* Creates new instance of <tt>UpdateActivator</tt>.
*/
public UpdateActivator() {
super(UpdateService.class, "Android update service");
}
/**
* Gets the <tt>ConfigurationService</tt> using current <tt>BundleContext</tt>.
*
* @return the <tt>ConfigurationService</tt>
*/
public static ConfigurationService getConfiguration() {
return ServiceUtils.getService(bundleContext, ConfigurationService.class);
}
/**
* {@inheritDoc}
*/
@Override
protected UpdateService createServiceImpl() {
return new UpdateServiceImpl();
}
/**
* {@inheritDoc}
*/
@Override
public void start(BundleContext bundleContext)
throws Exception {
UpdateActivator.bundleContext = bundleContext;
super.start(bundleContext);
((UpdateServiceImpl) serviceImpl).removeOldDownloads();
}
}
| 24.672131 | 80 | 0.747508 |
69cd24f45578910136569a2e042c9c88c38f7da3 | 24,271 | package com.tanyiqu.filesafe.activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.tanyiqu.filesafe.bean.FileSelectBean;
import com.tanyiqu.filesafe.R;
import com.tanyiqu.filesafe.data.Data;
import com.tanyiqu.filesafe.utils.FileUtil;
import com.tanyiqu.filesafe.utils.ScreenSizeUtil;
import com.tanyiqu.filesafe.utils.TypefaceUtil;
import com.tanyiqu.filesafe.utils.Util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
public class FileSelectActivity extends AppCompatActivity {
RecyclerView recycler;
LinearLayoutManager layoutManager;
Toolbar toolbar;
String currPath = Data.externalStoragePath;
String parentPath = null;
//上边显示路径
TextView path;
//adapter用于找到哪些是被选中的
FileAdapter adapter;
//记录当前在第几层
int floor = 1;
//记录所有层的第一个view的位置和偏移
int[] positions = new int[100];
int[] offset = new int[100];
//记录全选时当前的位置和偏移
int pos;
int off;
static Handler handler;
final int MSG_COPY_START = 0x12;
final int MSG_COPY_RUNNING = 0x34;
final int MSG_COPY_FINISH = 0x56;
//进度
int prog = 0;
//复制文件夹时的当前个数
int curr = 1;
//复制文件夹时的总数
int total;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_select);
init();
TypefaceUtil.replaceFont(this,"fonts/MiLan.ttf");
}
/**
* 初始化
*/
private void init() {
initToolBar();
initRecycler();
path = findViewById(R.id.tv_path);
//默认先进入根目录
enterDir(currPath,false);
currPath = Data.externalStoragePath;
parentPath = null;
}
/**
* 进入目录
* @param dirPath 目录路径
* @param isBack 是否为返回
*/
private void enterDir(String dirPath,boolean isBack) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
assert files != null;
//遍历文件夹
List<FileSelectBean> Dirs = new ArrayList<>();
List<FileSelectBean> Files = new ArrayList<>();
for(File f : files){
FileSelectBean item = new FileSelectBean();
if(f.isHidden()){
continue;
}
item.setParent(f.getParent());
item.setName(f.getName());
item.setDate(Util.transferLongToDate(f.lastModified()));
if(f.isDirectory()){//文件夹
item.setImgID(R.mipmap.ic_file_folder);
//计算出子文件数量,不加隐藏文件
int count = 0;
File[] sub = f.listFiles();
assert sub != null;
for(File subFile : sub){
if(subFile.isHidden()){
continue;
}
count++;
}
item.setSize(count + "项");
item.setDir(true);
Dirs.add(item);
}else { //文件
item.setImgID(FileUtil.getImgId(FileUtil.getFileExt(item.getName())));//根据扩展名,适配图标
item.setSize(Util.byteToSize(f.length()));
Files.add(item);
}
}
//排序 先按照中文升序,在按字母升序
Comparator<FileSelectBean> comparator = new Comparator<FileSelectBean>() {
@Override
public int compare(FileSelectBean l, FileSelectBean r) {
return Collator.getInstance(Locale.CHINESE).compare(l.getName(), r.getName());
}
};
Collections.sort(Dirs,comparator);
Collections.sort(Files,comparator);
//合并
Dirs.addAll(Files);
//显示
adapter = new FileAdapter(Dirs);
recycler.setAdapter(adapter);
adapter.syncCount();
//是返回操作就回到上次位置
if(isBack){
layoutManager.scrollToPositionWithOffset(positions[floor],offset[floor]);
}else {//不是返回操作才设置动画效果
recycler.setLayoutAnimation(DirsActivity.controller);
}
//更新路径
currPath = dirPath;
if(currPath.equals(Data.externalStoragePath)){
parentPath = null;
}else {
parentPath = dir.getParent();
}
//显示路径
path.setText(currPath.replace(Data.externalStoragePath,"内部存储设备"));
}
/**
* 初始化Recycler
*/
private void initRecycler() {
recycler = findViewById(R.id.recycler_file_select);
layoutManager = new LinearLayoutManager(this,RecyclerView.VERTICAL,false);
recycler.setLayoutManager(layoutManager);
recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
// Log.i("MyApp","滑动");
//当前为第floor层
//记录偏移
View firstView = layoutManager.getChildAt(0);
if(firstView != null){
offset[floor] = firstView.getTop();
positions[floor] = layoutManager.getPosition(firstView);
}
}
});
}
/**
* 初始化ToolBar
*/
private void initToolBar() {
toolbar = findViewById(R.id.toolbar_file_select);
toolbar.setTitle("选择文件");
toolbar.setSubtitle("0/29");
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
//添加菜单按钮
toolbar.inflateMenu(R.menu.menu_select_file_toolbar);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
//反选
case R.id.action_inverse_select:
//反选文件
adapter.inverseSelect();
//转到指定位置
layoutManager.scrollToPositionWithOffset(pos,off);
break;
//全选
case R.id.action_select_all:
//选择全部文件
adapter.selectAll();
//转到指定位置
layoutManager.scrollToPositionWithOffset(pos,off);
break;
//添加
case R.id.action_add_files:
return addFiles();
}
return false;
}
});
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
/**
* 添加文件
* @return 返回false,详见调用处
*/
private boolean addFiles(){
//获取已选择的文件列表
final List<String> paths = adapter.getSelected();
//如果没有选择文件,直接返回
if(paths.size() == 0){
Toast.makeText(FileSelectActivity.this, "请选择文件", Toast.LENGTH_SHORT).show();
return false;
}
//依次判断重复的文件
List<String> repeat = new ArrayList<>();
for(String path : paths){
//截取名字
String name = path.substring(path.lastIndexOf(File.separator) + 1);
//判断名字是否重复
if(fileIsExist(name)){
repeat.add(name);
}
}
//repeat里面的全部是重复的文件
if(repeat.size() != 0){//有重复的文件
StringBuilder sb = new StringBuilder();
sb.append("\"");
sb.append(repeat.get(0));
sb.append("\"\n");
if(repeat.size() >= 2){
sb.append("\"");
sb.append(repeat.get(1));
sb.append("\"...\n");
}
sb.append("等");
sb.append(repeat.size());
sb.append("个文件已存在");
new AlertDialog.Builder(FileSelectActivity.this)
.setTitle("警告")
.setMessage(sb)
.setPositiveButton("确定",null)
.show();
return false;
}
//现在paths里已经没有重复的文件了
//弹出对话框确认加密
new AlertDialog.Builder(FileSelectActivity.this)
.setMessage("确定加密选择的" + paths.size() + "个文件")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//加密所选的文件
//构造加密文件列表
List<File> oldFiles = new ArrayList<>();
List<File> newFiles = new ArrayList<>();
for(String path : paths){
//构造old
File oldFile = new File(path);
//构造new
//随机一个不重复的文件名
File newFile;
String newFileName;
do {
newFileName = Util.RandomName();
newFile = new File(FilesActivity.path, newFileName);
//如果文件已存在,重新随机一个
} while (newFile.exists());
oldFiles.add(oldFile);
newFiles.add(newFile);
//配置文件更新
Util.updateIni(new File(FilesActivity.path,"data.db"),
oldFile.getName(),
newFile.getName(),
oldFile.lastModified(),
oldFile.length());
}
copyDirDialog(FileSelectActivity.this,oldFiles,newFiles);
}
})
.setNegativeButton("取消",null)
.show();
return false;
}
/**
* 重写返回事件
*/
@Override
public void onBackPressed() {
//如果没有上一级,默认返回
if(currPath.equals(Data.externalStoragePath)){
super.onBackPressed();
overridePendingTransition(R.anim.anim_page_jump_3,R.anim.anim_page_jump_4);
FilesActivity.refreshFileView_list(FilesActivity.path);
}else{
//返回上一级
floor--;
enterDir(parentPath,true);
}
}
/**
* 重写onCreateOptionsMenu
* @param menu menu
* @return true or false
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_select_file_toolbar,menu);
return super.onCreateOptionsMenu(menu);
}
/**
* 判断文件在配置文件里是否已经存在
* 隐含条件:FilesActivity.path 为当前进入的目录
* @param name 文件名
* @return 是否已经存在
*/
public boolean fileIsExist(String name){
String iniPath = FilesActivity.path + File.separator + "data.db";
File iniFile = new File(iniPath);
boolean flag = false;
//检索是否出现 name
try {
FileReader in = new FileReader(iniFile);
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null){
String[] strings = line.split(Data.Splitter);
if(strings[0].equals(name)){//如果重复了
flag = true;
break;
}
}
br.close();
} catch (IOException e) {
return true;
}
return flag;
}
/**
* 显示复制文件的对话框兼复制文件功能
* Handler警告未消除。。
* @param context Context
* @param oldFiles 原始文件列表
* @param newFiles 新文件列表
*/
public void copyDirDialog(final Context context, final List<File> oldFiles, final List<File> newFiles){
if(oldFiles.size() == 0){
Toast.makeText(context, "空", Toast.LENGTH_SHORT).show();
return;
}
final Dialog dialog = new Dialog(context, R.style.NormalDialogStyle);
View v = View.inflate(context, R.layout.layout_dialog_copy, null);
final ProgressBar bar = v.findViewById(R.id.progress_bar);
final TextView title = v.findViewById(R.id.title);
final TextView tv_msg = v.findViewById(R.id.tv_msg);
final TextView progress = v.findViewById(R.id.progress);
final TextView confirm = v.findViewById(R.id.conform);
title.setText("正在复制");
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
handler = null;
finish();
overridePendingTransition(R.anim.anim_page_jump_3,R.anim.anim_page_jump_4);
//刷新显示
FilesActivity.refreshFileView_list(FilesActivity.path);
}
});
//Handler
if(handler == null){
handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MSG_COPY_START:
String t1 = "第"+curr+"/"+total+"个";
tv_msg.setText(t1);
break;
case MSG_COPY_FINISH:
title.setText("复制完成");
tv_msg.setText("");
confirm.setVisibility(View.VISIBLE);
case MSG_COPY_RUNNING:
bar.setProgress(prog);
String t2 = prog+"%";
progress.setText(t2);
break;
}
}
};
}
//Thread
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//循环复制文件
curr = 1;
for (int i=0;i<total;i++){
//提示正在开始复制第几个
handler.sendEmptyMessage(MSG_COPY_START);
prog = 0;
try {
long m = oldFiles.get(i).length();
int n = (int)(m/100);
int s = 0;//每一份的进度
FileInputStream fis = new FileInputStream(oldFiles.get(i));
FileOutputStream fos = new FileOutputStream(newFiles.get(i));
byte[] buffer = new byte[1024];
int byteRead;
while (-1 != (byteRead = fis.read(buffer))){
fos.write(buffer,0,byteRead);
s += 1024;
if(s >= n){//进度+1
handler.sendEmptyMessage(MSG_COPY_RUNNING);
prog ++;
s = 0;
}
}
fis.close();
fos.flush();
fos.close();
//复制完成1个
if(curr < total){
curr++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
prog = 100;
handler.sendEmptyMessage(MSG_COPY_FINISH);
}
});
total = oldFiles.size();
// 设置自定义的布局
dialog.setContentView(v);
//使得点击对话框外部不消失对话框
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
//设置对话框的大小
v.setMinimumHeight((int) (ScreenSizeUtil.getScreenHeight(context) * 0.15f));
Window dialogWindow = dialog.getWindow();
WindowManager.LayoutParams lp;
if (dialogWindow != null) {
lp = dialogWindow.getAttributes();
if (lp != null) {
lp.width = (int) (ScreenSizeUtil.getScreenWidth(context) * 0.88);
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.CENTER;
}
dialogWindow.setAttributes(lp);
}
dialog.show();
thread.start();
}
/**
* Adapter
* 内部类
*/
class FileAdapter extends RecyclerView.Adapter<FileAdapter.ViewHolder>{
private List<FileSelectBean> fileList;
private SparseBooleanArray checkStatus;
/**
* 构造
* @param fileList File列表
*/
FileAdapter(List<FileSelectBean> fileList) {
this.fileList = fileList;
checkStatus = new SparseBooleanArray();
//默认都未选中
for(int i=0;i<fileList.size();i++){
checkStatus.put(i,false);
}
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View root = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_files_item_select,parent,false);
return new ViewHolder(root);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
final FileSelectBean item = fileList.get(position);
holder.img_files_logo.setImageDrawable(getDrawable(item.getImgID()));
holder.tv_file_name.setText(item.getName());
holder.tv_file_size.setText(item.getSize());
holder.tv_file_date.setText(item.getDate());
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setVisibility(View.VISIBLE);
if(checkStatus.get(position)){
holder.checkBox.setChecked(true);
}else {
holder.checkBox.setChecked(false);
}
if(item.isDir()){
holder.checkBox.setVisibility(View.GONE);
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
checkStatus.put(position,true);
}else {
checkStatus.put(position,false);
}
}
});
//点击事件
holder.files_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(item.isDir()){
floor++;
enterDir(item.getParent() + File.separator + item.getName(),false);
}else {
//改变选中的状态
if(holder.checkBox.isChecked()){
holder.checkBox.setChecked(false);
}else{
holder.checkBox.setChecked(true);
}
syncCount();
}
}
});
//长按事件
holder.files_item.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
Toast.makeText(FileSelectActivity.this,"长按:" + item.getName(), Toast.LENGTH_SHORT).show();
return true;
}
});
}
@Override
public int getItemCount() {
return this.fileList.size();
}
/**
* 返回被选中的项
* @return 字符串列表形式返回
*/
List<String> getSelected(){
List<String> strings = new ArrayList<>();
for(int i=0;i<fileList.size();i++){
if(checkStatus.get(i)){
strings.add(fileList.get(i).getParent() + File.separator + fileList.get(i).getName());
}
}
return strings;
}
/**
* 同步选中的数目
* 在进入文件夹时、全选/反选时、点击文件时调用
*/
void syncCount(){
//获取总共可选的文件数
int totalCount = 0;
for(FileSelectBean item : fileList){
if(item.isDir()){
continue;
}
totalCount++;
}
int currCount = getSelected().size();
String s = currCount + "/" + totalCount;
toolbar.setSubtitle(s);
}
/**
* 全选
*/
void selectAll(){
//先将所有状态设为true
for(int i=0;i<fileList.size();i++){
FileSelectBean bean = fileList.get(i);
if(bean.isDir())
continue;
checkStatus.put(i,true);
}
//记录位置和偏移
View firstView = layoutManager.getChildAt(0);
if(firstView != null){
off = firstView.getTop();
pos = layoutManager.getPosition(firstView);
}
//刷新
recycler.setAdapter(this);
syncCount();
}
/**
* 反选
*/
void inverseSelect(){
for(int i=0;i<fileList.size();i++){
FileSelectBean bean = fileList.get(i);
if(bean.isDir())
continue;
if(checkStatus.get(i)){
checkStatus.put(i,false);
}else {
checkStatus.put(i,true);
}
}
//记录位置和偏移
View firstView = layoutManager.getChildAt(0);
if(firstView != null){
off = firstView.getTop();
pos = layoutManager.getPosition(firstView);
}
//刷新
recycler.setAdapter(this);
syncCount();
}
/**
* Holder
*/
class ViewHolder extends RecyclerView.ViewHolder{
ConstraintLayout files_item;
ImageView img_files_logo;
TextView tv_file_name;
TextView tv_file_size;
TextView tv_file_date;
CheckBox checkBox;
ViewHolder(@NonNull View itemView) {
super(itemView);
files_item = itemView.findViewById(R.id.files_item);
img_files_logo = itemView.findViewById(R.id.img_files_logo);
tv_file_name = itemView.findViewById(R.id.tv_file_name);
tv_file_size = itemView.findViewById(R.id.tv_file_size);
tv_file_date = itemView.findViewById(R.id.tv_file_date);
checkBox = itemView.findViewById(R.id.check);
}
}
}
}
| 33.850767 | 121 | 0.507519 |
ddfe76fbfa3680b731d652544bfa9f7142e1cd24 | 3,101 | package com.vaadin.flow.uitest.ui.template;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.vaadin.flow.component.html.testbench.NativeButtonElement;
import com.vaadin.flow.testutil.ChromeBrowserTest;
public class InnerTemplateVisibilityIT extends ChromeBrowserTest {
@Test
public void innerTemplateIsHiddenWithDisplayNone() {
open();
// when inner is hidden
NativeButtonElement toggleButton = $(NativeButtonElement.class)
.id(InnerTemplateVisibilityView.TOGGLE_INNER_VISIBILITY_BUTTON_ID);
toggleButton.click();
// then: element is not visible, attribute 'hidden' and 'display: none'
// set
WebElement outer = findElement(
By.id(InnerTemplateVisibilityView.OUTER_ID));
WebElement inner = findInShadowRoot(outer,
By.id(InnerTemplateVisibilityView.INNER_ID)).get(0);
Assert.assertFalse("expected inner to be hidden", inner.isDisplayed());
Assert.assertNotNull("expected attribute hidden on inner",
inner.getAttribute("hidden"));
Assert.assertEquals("expected 'display: none' on inner", "none",
inner.getCssValue("display"));
}
@Test
public void innerTemplateDisplayStyleRestored() {
open();
// when inner is hidden and unhidden
NativeButtonElement toggleButton = $(NativeButtonElement.class)
.id(InnerTemplateVisibilityView.TOGGLE_INNER_VISIBILITY_BUTTON_ID);
toggleButton.click();
toggleButton.click();
// then: element is visible, attribute and 'display: none' are no longer
// present
WebElement outer = findElement(
By.id(InnerTemplateVisibilityView.OUTER_ID));
WebElement inner = findInShadowRoot(outer,
By.id(InnerTemplateVisibilityView.INNER_ID)).get(0);
Assert.assertTrue("expected inner to be visible", inner.isDisplayed());
Assert.assertNull("inner should not have attribute hidden",
inner.getAttribute("hidden"));
Assert.assertEquals("expected 'display: block' on inner", "block",
inner.getCssValue("display"));
}
@Test
public void outerTemplateIsHiddenWithAttributeOnly() {
open();
// when hidden
NativeButtonElement toggleButton = $(NativeButtonElement.class)
.id(InnerTemplateVisibilityView.TOGGLE_OUTER_VISIBILITY_BUTTON_ID);
toggleButton.click();
// then: element is not visible, attribute 'hidden' is set but
// 'display: none' is not set
WebElement outer = findElement(
By.id(InnerTemplateVisibilityView.OUTER_ID));
Assert.assertFalse("expected outer to be hidden", outer.isDisplayed());
Assert.assertNotNull("expected attribute hidden on outer",
outer.getAttribute("hidden"));
Assert.assertEquals("expected no style attribute", "",
outer.getAttribute("style"));
}
}
| 39.75641 | 83 | 0.663334 |
40f224e8f3144d3ab4c892a5a3fe40932226cca2 | 17,177 | package com.bfo.json;
import java.util.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.*;
/**
* <p>
* This class controls the details of the {@link Json#read Json.read()} call.
* The various flags set on this class can control the read process, and in
* some cases (e.g. {@link #setStrictTypes}) determines how the objects behave
* after they are read.
* </p><p>
* The class uses a "fluent" style to enable setting multiple options at once, eg.
* </p>
* <pre>
* json.read(out, new JsonReadOptions().setAllowUnquotedKey(true).setAllowComments(true));
* </pre>
* <p>
* All flags default to false.
* </p>
*/
public class JsonReadOptions {
private boolean nfc;
private boolean unquotedKey;
private boolean trailingComma;
private boolean comments;
private boolean bigDecimal;
private boolean cborFailOnUnknownTypes;
private boolean failOnNonStringKeys;
private boolean nocontext;
private byte storeOptions;
private int fastStringLength = 262144;
private Filter filter;
private CodingErrorAction codingErrorAction = CodingErrorAction.REPLACE;
static final byte FLAG_STRICT = 1;
static final byte FLAG_LOOSEEMPTY = 2;
static final byte FLAG_CBOR = 4;
/**
* Whether to allow unquotedKey keys in the JSON input. This
* is not officially allowed, but still common. The default is false.
* @param unquotedKey the flag
* @return this
*/
public JsonReadOptions setAllowUnquotedKey(boolean unquotedKey) {
this.unquotedKey = unquotedKey;
return this;
}
/**
* Return the value of the "unquotedKey" flag as set by {@link #setAllowUnquotedKey}
* @return the flag
*/
public boolean isAllowUnquotedKey() {
return unquotedKey;
}
/**
* Whether to allow trailing commas in the JSON input, eg <code>["a",]</code>. This
* is not officially allowed, but still common.
* @param trailingComma the flag
* @return this
*/
public JsonReadOptions setAllowTrailingComma(boolean trailingComma) {
this.trailingComma = trailingComma;
return this;
}
/**
* Return the value of the "trailingComma" flag as set by {@link #setAllowTrailingComma}
* @return the flag
*/
public boolean isAllowTrailingComma() {
return trailingComma;
}
/**
* Whether to allow comments in the JSON input, eg <code>["a"]/*comment*/</code>. This
* is not officially allowed, but still common.
* @param comments the flag
* @return this
*/
public JsonReadOptions setAllowComments(boolean comments) {
this.comments = comments;
return this;
}
/**
* Return the value of the "comments" flag as set by {@link #setAllowComments}
* @return the flag
*/
public boolean isAllowComments() {
return comments;
}
/**
* Whether to turn off tracking of the line, column and context of the reader when
* reading from a file, which is used when reporting errors. This is on by default,
* but slows down reading by about 1.5%
* @param nocontext the flag
* @return this
*/
public JsonReadOptions setContextFree(boolean nocontext) {
this.nocontext = nocontext;
return this;
}
/**
* Return the value of the "nocontext" flag as set by {@link #setContextFree}
* @return the flag
*/
public boolean isContextFree() {
return nocontext;
}
/**
* Set whether to normalize all Strings (including map keys) to Unicode {@link java.text.Normalizer.Form#NFC normal form C}
* @param nfc the flag
* @return this
*/
public JsonReadOptions setNFC(boolean nfc) {
this.nfc = nfc;
return this;
}
/**
* Return the value of the "nfc" flag as set by {@link #setNFC}
* @return the flag
*/
public boolean isNFC() {
return nfc;
}
/**
* Set whether real numbers that cannot be guaranteed to be exactly the same when stored as
* a {@link java.lang.Double} should be stored as a {@link java.math.BigDecimal}.
* The default is false, which means every real number read by the JsonReader will
* be converted to a Double.
* @param bigDecimal the flag
* @return this
*/
public JsonReadOptions setBigDecimal(boolean bigDecimal) {
this.bigDecimal = bigDecimal;
return this;
}
/**
* Return the value of the "bigDecimal" flag as set by {@link #setBigDecimal}
* @return the flag
*/
public boolean isBigDecimal() {
return bigDecimal;
}
/**
* Determines whether objects read by the JsonReader will be loosely typed. With this
* flag set, calling {@link Json#intValue} on the string "123" will result in a
* {@link ClassCastException} being thrown rather than a silent conversion to integer.
* @param strictTypes the flag
* @return this
*/
public JsonReadOptions setStrictTypes(boolean strictTypes) {
if (strictTypes) {
storeOptions |= FLAG_STRICT;
} else {
storeOptions &= ~FLAG_STRICT;
}
return this;
}
/**
* Return the value of the "strictTypes" flag as set by {@link #setStrictTypes}
* @return the flag
*/
public boolean isStrictTypes() {
return (storeOptions & FLAG_STRICT) != 0;
}
/**
* When the {@link #setStrictTypes strictTypes} flag is not set, this flag will determine
* whether empty strings evaluate to zero when treated as a number and false when treated
* as a boolean.
* @param looseEmptyStrings the flag
* @return this
*/
public JsonReadOptions setLooseEmptyStrings(boolean looseEmptyStrings) {
if (looseEmptyStrings) {
storeOptions |= FLAG_LOOSEEMPTY;
} else {
storeOptions &= ~FLAG_LOOSEEMPTY;
}
return this;
}
/**
* Return the value of the "looseEmptyString" flag as set by {@link #setLooseEmptyStrings}
* @return the flag
*/
public boolean isLooseEmptyStrings() {
return (storeOptions & FLAG_LOOSEEMPTY) != 0;
}
byte storeOptions() {
return storeOptions;
}
/**
* When reading CBOR/Msgpack, if a String is encountered where the UTF-8 encoding
* is incorrect, the specified action will be performed.
* The default is {@link CodingErrorAction#REPLACE}
* @param action the action
* @return this
* @since 2
*/
public JsonReadOptions setCborStringCodingErrorAction(CodingErrorAction action) {
this.codingErrorAction = action;
return this;
}
/**
* Return the CodingErrorAction set by {@link #setCborStringCodingErrorAction}
* is incorrect, the specified action will be performed.
* The default is {@link CodingErrorAction#REPLACE}, which is also the fastest
* option.
* @return the action
* @since 2
*/
public CodingErrorAction getCborStringCodingErrorAction() {
return codingErrorAction;
}
/**
* When reading a CBOR stream that contains undefined, but technically valid types,
* by default these will be collapsed to null with a tag set on them to indicate the
* original type. Setting this flag will, instead, cause the stream to fail.
* @param flag the flag
* @return this
* @since 2
*/
public JsonReadOptions setCborFailOnUnknownTypes(boolean flag) {
cborFailOnUnknownTypes = flag;
return this;
}
/**
* Return the value of the "cborFailOnUnknownTypes" flag, as set by
* {@link setCborFailOnUnknownTypes}
* @since 2
* @return the flag
*/
public boolean isCborFailOnUnknownTypes() {
return cborFailOnUnknownTypes;
}
/**
* When reading CBOR/Msgpack and a map key is encountered that is not a String,
* fail rather than converting it silently to a String. This API (and Json) only
* allow map keys to be strings.
* @param flag the flag
* @return this
* @since 3
*/
public JsonReadOptions setFailOnNonStringKeys(boolean flag) {
failOnNonStringKeys = flag;
return this;
}
/**
* Return the value of the "failOnNonStringKeys" flag, as set by
* {@link #setFailOnNonStringKeys}
* @since 3
* @return the flag
*/
public boolean isFailOnNonStringKeys() {
return failOnNonStringKeys;
}
/**
* Set the value of the "fastStringLength" value - strings loaded from a binary source
* less than this value will be loaded directly into memory, whereas above this length
* they will be streamed. The default is 262144 (256KB).
* @param len the length
* @since 4
* @return this
*/
public JsonReadOptions setFastStringLength(int len) {
fastStringLength = len;
return this;
}
/**
* Return the value of the "fastStringLength" as set by {@link #setFastStringLength}
* @since 4
* @return the fastStringLength value
*/
public int getFastStringLength() {
return fastStringLength;
}
/**
* Set the {@link Filter} that will be used to convert objects when reading
* @param filter the filter, or null for no filter
* @return this
* @since 4
*/
public JsonReadOptions setFilter(Filter filter) {
this.filter = filter;
return this;
}
/**
* Return the value of the Filter as set by {@link #setFilter}
* @since 4
* @return the filter
*/
public Filter getFilter() {
return filter;
}
/**
* A Filter which can be applied during reading of data. The
* interface will have its enter/exit methods called to show
* where in the input data is being read, and the various
* "create" methods can be overridden if necessary. For example,
* if a field is known to be particularly large:
* <pre>
* JsonReadOptions.Filter f = new JsonReadOptions.Filter() {
* public void enter(Json parent, Json key) {
* where.append("." + key);
* }
* public void exit(Json parent, Json key) {
* where = where.substring(0, where.lastIndexOf("."));
* }
* public void createBuffer(InputStream in, long length) {
* if (where.toString().equals("large.file.data")) {
* final Path path = Paths.get("largefile");
* Json j = new Json(ByteBuffer.allocate(0)) {
* protected void writeBuffer(OutputStream out) {
* Files.copy(path, out);
* }
* };
* Files.copy(in, path);
* } else {
* return super.createBuffer(in, length);
* }
* }
* }
* </pre>
* @since 4
*/
public static class Filter {
/**
* Called once when the Json reading begins
* @throws IOException if an error occurs during processing
*/
public void initialize() throws IOException {
}
/**
* Called once when the Json reading ends
* @param json the completed object
* @throws IOException if an error occurs during processing
*/
public void complete(Json json) throws IOException {
}
/**
* Called before reading each entry in a Map.
* @param parent the current map
* @param key the key of the next entry in the map
* @throws IOException if an error occurs during processing
*/
public void enter(Json parent, String key) throws IOException {
}
/**
* Called after reading each entry in a Map.
* @param parent the current map
* @param key the key of the entry just read in the map
* @throws IOException if an error occurs during processing
*/
public void exit(Json parent, String key) throws IOException {
}
/**
* Called before reading each entry in a List.
* @param parent the current list
* @param key the key of the next entry in the list
* @throws IOException if an error occurs during processing
*/
public void enter(Json parent, int key) throws IOException {
}
/**
* Called after reading each entry in a List.
* @param parent the current list
* @param key the key of the entry just read in the list
* @throws IOException if an error occurs during processing
*/
public void exit(Json parent, int key) throws IOException {
}
/**
* Create a new "map" object
* @return the new Json object
* @throws IOException if an error occurs during reading
*/
public Json createMap() throws IOException {
return new Json(Collections.EMPTY_MAP, null);
}
/**
* Create a new "list" object
* @return the new Json object
* @throws IOException if an error occurs during reading
*/
public Json createList() throws IOException {
return new Json(Collections.EMPTY_LIST, null);
}
/**
* Create a new "null" object
* @return the new Json object
* @throws IOException if an error occurs during reading
*/
public Json createNull() throws IOException {
return new Json(null, null);
}
/**
* Create a new "boolean" object
* @param b the boolean
* @return the new Json object
* @throws IOException if an error occurs during reading
*/
public Json createBoolean(boolean b) throws IOException {
return new Json(b, null);
}
/**
* Create a new "number" object
* @param n the number
* @return the new Json object
* @throws IOException if creation failed
*/
public Json createNumber(Number n) throws IOException {
return new Json(n, null);
}
/**
* Create a new "string" object
* @param in the reader to read the string from
* @param length the number of characters that will be read from reader, or -1 if unknown
* @return the new Json object
* @throws IOException if an error occurs during reading
*/
public Json createString(Reader in, long length) throws IOException {
if (in instanceof StringReader) {
String s = in.toString();
return new Json(s, null);
} else if (in instanceof JsonReader.JsonStringReader) {
return new Json(((JsonReader.JsonStringReader)in).readString(), null);
} else if (length > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Can't allocate "+length+" String");
} else if (length >= 0) {
char[] buf = new char[(int)length];
int c, off = 0;
while ((c=in.read(buf, off, buf.length - off)) >= 0) {
off += c;
}
if (off != buf.length) {
throw new EOFException();
}
return new Json(java.nio.CharBuffer.wrap(buf, 0, buf.length), null);
} else {
StringBuilder sb = new StringBuilder(8192);
char[] buf = new char[8192];
int c;
while ((c=in.read(buf, 0, buf.length)) >= 0) {
sb.append(buf, 0, c);
}
return new Json(sb.toString(), null);
}
}
/**
* Create a new "buffer" object
* @param in the InputStream to read the buffer from
* @param length the number of bytes that will be read from reader, or -1 if unknown
* @return the new Json object
* @throws IOException if an error occurs during reading
*/
public Json createBuffer(InputStream in, long length) throws IOException {
if (length > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Can't allocate "+length+" ByteBuffer");
} else if (length >= 0) {
byte[] buf = new byte[(int)length];
int c, off = 0;
while ((c=in.read(buf, off, buf.length - off)) >= 0) {
off += c;
}
if (off != buf.length) {
throw new EOFException();
}
return new Json(ByteBuffer.wrap(buf, 0, buf.length), null);
} else {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int c;
while ((c=in.read(buf)) >= 0) {
out.write(buf, 0, c);
}
buf = out.toByteArray();
return new Json(ByteBuffer.wrap(buf, 0, buf.length), null);
}
}
}
}
| 32.655894 | 127 | 0.590906 |
b641f1f8caf8e369c3fa5a84a95e1bcaa58ed572 | 1,040 | package com.ineat.sample.quickadapter.itemrenderer;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;
import com.ineat.quickadapter.QuickItemRenderer;
import com.ineat.quickadapter.QuickLayout;
import com.ineat.quickadapter.sample.R;
import com.ineat.sample.quickadapter.Ineatien;
/**
* Created by mslimani on 08/10/2016.
*/
@QuickLayout(R.layout.item_ineatien)
public class IneatienQuickItemRenderer extends QuickItemRenderer<Ineatien> {
private TextView mFirstnameTextView;
private TextView mLastnameTextView;
public IneatienQuickItemRenderer(View itemView) {
super(itemView);
mFirstnameTextView = (TextView) itemView.findViewById(R.id.text_firstname);
mLastnameTextView = (TextView) itemView.findViewById(R.id.text_lastname);
}
@Override
public void onBind(int position, @NonNull Ineatien ineatien) {
mFirstnameTextView.setText(ineatien.getFirstName());
mLastnameTextView.setText(ineatien.getLastName());
}
}
| 30.588235 | 83 | 0.769231 |
5b61142009d69d87baafb26170763526239fd8e0 | 1,342 | package org.vitrivr.cineast.api.messages.session;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.vitrivr.cineast.api.messages.credentials.Credentials;
import org.vitrivr.cineast.api.messages.interfaces.Message;
import org.vitrivr.cineast.api.messages.interfaces.MessageType;
/**
* Message from the requester to transfer the access credentials of the current session.
*/
public class StartSessionMessage implements Message {
/**
* {@link Credentials} of the session with the user.
*/
private final Credentials credentials;
/**
* Constructor for the StartSessionMessage object.
*
* @param credentials Credentials of the current session from the user.
*/
@JsonCreator
public StartSessionMessage(@JsonProperty("credentials") Credentials credentials) {
this.credentials = credentials;
}
public Credentials getCredentials() {
return this.credentials;
}
/**
* {@inheritDoc}
*/
@Override
public MessageType getMessageType() {
return MessageType.SESSION_START;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.JSON_STYLE);
}
}
| 27.958333 | 88 | 0.763785 |
127a49e64c0d314d903260ce0704a5678eb9ab59 | 4,264 | package cn.zqmy.monkeytool.cache.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Redis 基础操作工具类
* @Author: zhuoqianmingyue
* @Date: 2021/04/15
* @Description:
**/
public class BaseRedisUtil {
@Autowired
protected RedisTemplate<String, Object> redisTemplate;
/**
* 指定缓存失效时间(expire key seconds)
*
* @param key 建
* @param timeout 失效时间(单位:秒,小于等于0 表示 永久有效)
*/
public void expire(String key, long timeout) {
try {
if (timeout > 0) {
redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
} catch (Exception e) {
throw new RuntimeException("指定缓存失效时间 异常:", e);
}
}
/**
* 取 key键 的失效时间(ttl key)
*
* @param key 键
* @return 失效时间(单位:秒)
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断 key键 是否存在(exists key)
*
* @param key 键
* @return 存在:true;不存在:false
*/
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 删除key键数组的缓存(del key)
*
* @param keys 要删除缓存的key键 数组
*/
public void del(String... keys) {
if(null != keys && keys.length > 0){
redisTemplate.delete(CollectionUtils.arrayToList(keys));
}
}
/**
* 按照 key值前缀 批量删除 缓存
*
* @param prex key值前缀
*/
public void delByPrex(String prex) {
Set<String> keys = redisTemplate.keys(prex);
if (!CollectionUtils.isEmpty(keys)) {
redisTemplate.delete(keys);
}
}
/**
* 从当前数据库中随机返回一个 key
*
* @return
*/
public String randomKey() {
return redisTemplate.randomKey();
}
/**
* 修改 key 的名称
*
* @param oldKey
* @param newKey
*/
public void rename(String oldKey, String newKey) {
redisTemplate.rename(oldKey, newKey);
}
/**
* 仅当 newkey 不存在时,将 oldKey 改名为 newkey
*
* @param oldKey
* @param newKey
* @return
*/
public Boolean renameIfAbsent(String oldKey, String newKey) {
return redisTemplate.renameIfAbsent(oldKey, newKey);
}
/**
* 返回 key 所储存的值的类型
*
* @param key
* @return
*/
public DataType type(String key) {
return redisTemplate.type(key);
}
/**
* 将当前数据库的 key 移动到给定的数据库 db 当中
*
* @param key
* @param dbIndex
* @return
*/
public Boolean move(String key, int dbIndex) {
return redisTemplate.move(key, dbIndex);
}
/**
* 使用scan命令 查询某些前缀的key
*
* @param key
* @return
*/
public Set<String> scan(String key) {
return this.redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Set<String> binaryKeys = new HashSet<>();
Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(key).count(1000).build());
while (cursor.hasNext()) {
binaryKeys.add(new String(cursor.next()));
}
return binaryKeys;
});
}
/**
* 使用scan命令 查询某些前缀的key 有多少个
*
* @param key
* @return
*/
public Long scanSize(String key) {
return this.redisTemplate.execute((RedisCallback<Long>) connection -> {
long count = 0L;
Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(key).count(1000).build());
while (cursor.hasNext()) {
cursor.next();
count++;
}
return count;
});
}
}
| 24.090395 | 121 | 0.584662 |
a7f7a4741ca9d41debb8556b1ed1f48a9a78ee89 | 509 | package com.scheduler.managerserver.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 模型集成
* @Author: wangming
* @Date: 2020-05-26 10:20
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ComputerServerInfo {
String oid;
String name;
String description;
String author_name;
String author_oid;
String contentType;
String createTime;
String pid;
String mdlJson;
String mdl;
}
| 17.551724 | 39 | 0.726916 |
78f0d5d9f049aeb534357e9c62cbb591a5b71e0b | 2,690 | package DataStructureStrArrayDeque;
import java.util.ArrayList;
import java.util.List;
public class CsvParser_STR {
/*
* How to parse csv file:
input file
“some_name|some_address|some_phone|some_job”,
output
Json format “{name:some_name, address:some_addres,phone:some_phone, job:some_job}”
Note:
need to consider quote, escape \ cases. The quote between quote is escaped
*/
/*
Parse CSV file: a simplified version
John, Smith, [email protected], Los Angeles, 1
Jane, Roberts, [email protected], "San Francisco, CA", 0
"Alexandra ""Alex""", Menendez, [email protected], Miami, 1
"""Alexandra Alex"""
John| Smith | [email protected] | Los Angeles | 1
Jane| Roberts| [email protected]| San Francisco, CA| 0
Alexandra "Alex"| Menendez| [email protected]| Miami| 1
"Alexandra Alex"
*/
// Algorithm: String with state machine flag
public List<String> parseLine(String line) {
List<String> res = new ArrayList<>();
StringBuilder tokenSB = new StringBuilder();
boolean inquote = false;
String l = line.trim();
for (int i = 0; i < l.length(); i++) {
char c = l.charAt(i);
if (c == ',') {
if (inquote) {
tokenSB.append(',');
} else {
res.add(tokenSB.toString());
tokenSB.setLength(0); // clean up
}
} else if (c == '\"') {
if (!inquote) {
inquote = true;
} else {
if (l.charAt(i + 1) == '\"') {
System.out.println("here i " + i);
tokenSB.append('\"');
i++;
} else {
inquote = false;
}
}
} else {
tokenSB.append(c);
}
}
res.add(tokenSB.toString());
return res;
}
public static void main(String[] args) {
String s = " \"Alexandra \"\"Alex\"\"\", Menendez, [email protected], \"Miami, FL\", 1";
CsvParser_STR outer = new CsvParser_STR();
System.out.println(outer.parseLine(s));
}
}
| 34.935065 | 121 | 0.430855 |
cd4f166779689911fbd50a053dfcb3027d668f5b | 4,682 | /* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://fedora-commons.org/license/).
*/
package org.fcrepo.server.management;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.fcrepo.common.Constants;
import org.fcrepo.server.Context;
import org.fcrepo.server.ReadOnlyContext;
import org.fcrepo.server.Server;
import org.fcrepo.server.errors.InitializationException;
import org.fcrepo.server.errors.authorization.AuthzException;
import org.fcrepo.server.errors.servletExceptionExtensions.RootException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Accepts and HTTP Multipart POST of a file from an authorized user, and if
* successful, returns a status of "201 Created" and a text/plain response with
* a single line containing an opaque identifier that can be used to later
* submit to the appropriate API-M method.
* <p>
* If it fails it will return a non-201 status code with a text/plain
* explanation. The submitted file must be named "file".
*
* @author Chris Wilper
*/
public class UploadServlet
extends SpringManagementServlet {
private static final Logger logger =
LoggerFactory.getLogger(UploadServlet.class);
private static final long serialVersionUID = 1L;
/**
* The servlet entry point. http://host:port/fedora/management/upload
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Context context =
ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri,
request);
try {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request, looking for "file"
InputStream in = null;
FileItemIterator iter = upload.getItemIterator(request);
while (in == null && iter.hasNext()) {
FileItemStream item = iter.next();
logger.info("Got next item: isFormField=" + item.isFormField() + " fieldName=" + item.getFieldName());
if (!item.isFormField() && item.getFieldName().equals("file")) {
in = item.openStream();
}
}
if (in == null) {
sendResponse(HttpServletResponse.SC_BAD_REQUEST,
"No data sent.",
response);
} else {
sendResponse(HttpServletResponse.SC_CREATED,
m_management.putTempStream(context, in),
response);
}
} catch (AuthzException ae) {
throw RootException.getServletException(ae,
request,
"Upload",
new String[0]);
} catch (Exception e) {
e.printStackTrace();
sendResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e
.getClass().getName()
+ ": " + e.getMessage(), response);
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
sendResponse(HttpServletResponse.SC_OK,
"Client must use HTTP Multipart POST",
response);
}
public void sendResponse(int status,
String message,
HttpServletResponse response) {
try {
if (status == HttpServletResponse.SC_CREATED) {
logger.info("Successful upload, id=" + message);
} else {
logger.error("Failed upload: " + message);
}
response.setStatus(status);
response.setContentType("text/plain");
PrintWriter w = response.getWriter();
w.println(message);
} catch (Exception e) {
logger.error("Unable to send response", e);
}
}
}
| 37.758065 | 118 | 0.605938 |
65415182099bd44b967ccda0537e7877dca41a2c | 210 | package calendar;
public interface Effect {
public void init();
public void mouse();
public void keyboard();
public void reshape(int width, int height);
public void display();
public String getName();
}
| 19.090909 | 44 | 0.728571 |
7c3512b8b5d72596a3ee4ef13723e728fcbf8dd1 | 21,350 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v4.view.accessibility;
import android.os.Parcelable;
import android.view.View;
import android.view.accessibility.AccessibilityRecord;
import java.util.List;
// Referenced classes of package android.support.v4.view.accessibility:
// AccessibilityNodeInfoCompat
public class AccessibilityRecordCompat
{
public AccessibilityRecordCompat(Object obj)
{
// 0 0:aload_0
// 1 1:invokespecial #12 <Method void Object()>
mRecord = (AccessibilityRecord)obj;
// 2 4:aload_0
// 3 5:aload_1
// 4 6:checkcast #14 <Class AccessibilityRecord>
// 5 9:putfield #16 <Field AccessibilityRecord mRecord>
// 6 12:return
}
public static int getMaxScrollX(AccessibilityRecord accessibilityrecord)
{
if(android.os.Build.VERSION.SDK_INT >= 15)
//* 0 0:getstatic #26 <Field int android.os.Build$VERSION.SDK_INT>
//* 1 3:bipush 15
//* 2 5:icmplt 13
return accessibilityrecord.getMaxScrollX();
// 3 8:aload_0
// 4 9:invokevirtual #29 <Method int AccessibilityRecord.getMaxScrollX()>
// 5 12:ireturn
else
return 0;
// 6 13:iconst_0
// 7 14:ireturn
}
public static int getMaxScrollY(AccessibilityRecord accessibilityrecord)
{
if(android.os.Build.VERSION.SDK_INT >= 15)
//* 0 0:getstatic #26 <Field int android.os.Build$VERSION.SDK_INT>
//* 1 3:bipush 15
//* 2 5:icmplt 13
return accessibilityrecord.getMaxScrollY();
// 3 8:aload_0
// 4 9:invokevirtual #32 <Method int AccessibilityRecord.getMaxScrollY()>
// 5 12:ireturn
else
return 0;
// 6 13:iconst_0
// 7 14:ireturn
}
public static AccessibilityRecordCompat obtain()
{
return new AccessibilityRecordCompat(((Object) (AccessibilityRecord.obtain())));
// 0 0:new #2 <Class AccessibilityRecordCompat>
// 1 3:dup
// 2 4:invokestatic #37 <Method AccessibilityRecord AccessibilityRecord.obtain()>
// 3 7:invokespecial #39 <Method void AccessibilityRecordCompat(Object)>
// 4 10:areturn
}
public static AccessibilityRecordCompat obtain(AccessibilityRecordCompat accessibilityrecordcompat)
{
return new AccessibilityRecordCompat(((Object) (AccessibilityRecord.obtain(accessibilityrecordcompat.mRecord))));
// 0 0:new #2 <Class AccessibilityRecordCompat>
// 1 3:dup
// 2 4:aload_0
// 3 5:getfield #16 <Field AccessibilityRecord mRecord>
// 4 8:invokestatic #43 <Method AccessibilityRecord AccessibilityRecord.obtain(AccessibilityRecord)>
// 5 11:invokespecial #39 <Method void AccessibilityRecordCompat(Object)>
// 6 14:areturn
}
public static void setMaxScrollX(AccessibilityRecord accessibilityrecord, int i)
{
if(android.os.Build.VERSION.SDK_INT >= 15)
//* 0 0:getstatic #26 <Field int android.os.Build$VERSION.SDK_INT>
//* 1 3:bipush 15
//* 2 5:icmplt 13
accessibilityrecord.setMaxScrollX(i);
// 3 8:aload_0
// 4 9:iload_1
// 5 10:invokevirtual #48 <Method void AccessibilityRecord.setMaxScrollX(int)>
// 6 13:return
}
public static void setMaxScrollY(AccessibilityRecord accessibilityrecord, int i)
{
if(android.os.Build.VERSION.SDK_INT >= 15)
//* 0 0:getstatic #26 <Field int android.os.Build$VERSION.SDK_INT>
//* 1 3:bipush 15
//* 2 5:icmplt 13
accessibilityrecord.setMaxScrollY(i);
// 3 8:aload_0
// 4 9:iload_1
// 5 10:invokevirtual #51 <Method void AccessibilityRecord.setMaxScrollY(int)>
// 6 13:return
}
public static void setSource(AccessibilityRecord accessibilityrecord, View view, int i)
{
if(android.os.Build.VERSION.SDK_INT >= 16)
//* 0 0:getstatic #26 <Field int android.os.Build$VERSION.SDK_INT>
//* 1 3:bipush 16
//* 2 5:icmplt 14
accessibilityrecord.setSource(view, i);
// 3 8:aload_0
// 4 9:aload_1
// 5 10:iload_2
// 6 11:invokevirtual #57 <Method void AccessibilityRecord.setSource(View, int)>
// 7 14:return
}
public boolean equals(Object obj)
{
if(this == obj)
//* 0 0:aload_0
//* 1 1:aload_1
//* 2 2:if_acmpne 7
return true;
// 3 5:iconst_1
// 4 6:ireturn
if(obj == null)
//* 5 7:aload_1
//* 6 8:ifnonnull 13
return false;
// 7 11:iconst_0
// 8 12:ireturn
if(((Object)this).getClass() != obj.getClass())
//* 9 13:aload_0
//* 10 14:invokevirtual #64 <Method Class Object.getClass()>
//* 11 17:aload_1
//* 12 18:invokevirtual #64 <Method Class Object.getClass()>
//* 13 21:if_acmpeq 26
return false;
// 14 24:iconst_0
// 15 25:ireturn
obj = ((Object) ((AccessibilityRecordCompat)obj));
// 16 26:aload_1
// 17 27:checkcast #2 <Class AccessibilityRecordCompat>
// 18 30:astore_1
AccessibilityRecord accessibilityrecord = mRecord;
// 19 31:aload_0
// 20 32:getfield #16 <Field AccessibilityRecord mRecord>
// 21 35:astore_2
if(accessibilityrecord == null)
//* 22 36:aload_2
//* 23 37:ifnonnull 49
{
if(((AccessibilityRecordCompat) (obj)).mRecord != null)
//* 24 40:aload_1
//* 25 41:getfield #16 <Field AccessibilityRecord mRecord>
//* 26 44:ifnull 62
return false;
// 27 47:iconst_0
// 28 48:ireturn
} else
if(!((Object) (accessibilityrecord)).equals(((Object) (((AccessibilityRecordCompat) (obj)).mRecord))))
//* 29 49:aload_2
//* 30 50:aload_1
//* 31 51:getfield #16 <Field AccessibilityRecord mRecord>
//* 32 54:invokevirtual #66 <Method boolean Object.equals(Object)>
//* 33 57:ifne 62
return false;
// 34 60:iconst_0
// 35 61:ireturn
return true;
// 36 62:iconst_1
// 37 63:ireturn
}
public int getAddedCount()
{
return mRecord.getAddedCount();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #69 <Method int AccessibilityRecord.getAddedCount()>
// 3 7:ireturn
}
public CharSequence getBeforeText()
{
return mRecord.getBeforeText();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #73 <Method CharSequence AccessibilityRecord.getBeforeText()>
// 3 7:areturn
}
public CharSequence getClassName()
{
return mRecord.getClassName();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #76 <Method CharSequence AccessibilityRecord.getClassName()>
// 3 7:areturn
}
public CharSequence getContentDescription()
{
return mRecord.getContentDescription();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #79 <Method CharSequence AccessibilityRecord.getContentDescription()>
// 3 7:areturn
}
public int getCurrentItemIndex()
{
return mRecord.getCurrentItemIndex();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #82 <Method int AccessibilityRecord.getCurrentItemIndex()>
// 3 7:ireturn
}
public int getFromIndex()
{
return mRecord.getFromIndex();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #85 <Method int AccessibilityRecord.getFromIndex()>
// 3 7:ireturn
}
public Object getImpl()
{
return ((Object) (mRecord));
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:areturn
}
public int getItemCount()
{
return mRecord.getItemCount();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #90 <Method int AccessibilityRecord.getItemCount()>
// 3 7:ireturn
}
public int getMaxScrollX()
{
return getMaxScrollX(mRecord);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokestatic #92 <Method int getMaxScrollX(AccessibilityRecord)>
// 3 7:ireturn
}
public int getMaxScrollY()
{
return getMaxScrollY(mRecord);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokestatic #94 <Method int getMaxScrollY(AccessibilityRecord)>
// 3 7:ireturn
}
public Parcelable getParcelableData()
{
return mRecord.getParcelableData();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #98 <Method Parcelable AccessibilityRecord.getParcelableData()>
// 3 7:areturn
}
public int getRemovedCount()
{
return mRecord.getRemovedCount();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #101 <Method int AccessibilityRecord.getRemovedCount()>
// 3 7:ireturn
}
public int getScrollX()
{
return mRecord.getScrollX();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #104 <Method int AccessibilityRecord.getScrollX()>
// 3 7:ireturn
}
public int getScrollY()
{
return mRecord.getScrollY();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #107 <Method int AccessibilityRecord.getScrollY()>
// 3 7:ireturn
}
public AccessibilityNodeInfoCompat getSource()
{
return AccessibilityNodeInfoCompat.wrapNonNullInstance(((Object) (mRecord.getSource())));
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #112 <Method android.view.accessibility.AccessibilityNodeInfo AccessibilityRecord.getSource()>
// 3 7:invokestatic #118 <Method AccessibilityNodeInfoCompat AccessibilityNodeInfoCompat.wrapNonNullInstance(Object)>
// 4 10:areturn
}
public List getText()
{
return mRecord.getText();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #122 <Method List AccessibilityRecord.getText()>
// 3 7:areturn
}
public int getToIndex()
{
return mRecord.getToIndex();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #127 <Method int AccessibilityRecord.getToIndex()>
// 3 7:ireturn
}
public int getWindowId()
{
return mRecord.getWindowId();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #130 <Method int AccessibilityRecord.getWindowId()>
// 3 7:ireturn
}
public int hashCode()
{
AccessibilityRecord accessibilityrecord = mRecord;
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:astore_1
if(accessibilityrecord == null)
//* 3 5:aload_1
//* 4 6:ifnonnull 11
return 0;
// 5 9:iconst_0
// 6 10:ireturn
else
return ((Object) (accessibilityrecord)).hashCode();
// 7 11:aload_1
// 8 12:invokevirtual #133 <Method int Object.hashCode()>
// 9 15:ireturn
}
public boolean isChecked()
{
return mRecord.isChecked();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #137 <Method boolean AccessibilityRecord.isChecked()>
// 3 7:ireturn
}
public boolean isEnabled()
{
return mRecord.isEnabled();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #140 <Method boolean AccessibilityRecord.isEnabled()>
// 3 7:ireturn
}
public boolean isFullScreen()
{
return mRecord.isFullScreen();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #143 <Method boolean AccessibilityRecord.isFullScreen()>
// 3 7:ireturn
}
public boolean isPassword()
{
return mRecord.isPassword();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #146 <Method boolean AccessibilityRecord.isPassword()>
// 3 7:ireturn
}
public boolean isScrollable()
{
return mRecord.isScrollable();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #149 <Method boolean AccessibilityRecord.isScrollable()>
// 3 7:ireturn
}
public void recycle()
{
mRecord.recycle();
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:invokevirtual #152 <Method void AccessibilityRecord.recycle()>
// 3 7:return
}
public void setAddedCount(int i)
{
mRecord.setAddedCount(i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #155 <Method void AccessibilityRecord.setAddedCount(int)>
// 4 8:return
}
public void setBeforeText(CharSequence charsequence)
{
mRecord.setBeforeText(charsequence);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:aload_1
// 3 5:invokevirtual #159 <Method void AccessibilityRecord.setBeforeText(CharSequence)>
// 4 8:return
}
public void setChecked(boolean flag)
{
mRecord.setChecked(flag);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #163 <Method void AccessibilityRecord.setChecked(boolean)>
// 4 8:return
}
public void setClassName(CharSequence charsequence)
{
mRecord.setClassName(charsequence);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:aload_1
// 3 5:invokevirtual #166 <Method void AccessibilityRecord.setClassName(CharSequence)>
// 4 8:return
}
public void setContentDescription(CharSequence charsequence)
{
mRecord.setContentDescription(charsequence);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:aload_1
// 3 5:invokevirtual #169 <Method void AccessibilityRecord.setContentDescription(CharSequence)>
// 4 8:return
}
public void setCurrentItemIndex(int i)
{
mRecord.setCurrentItemIndex(i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #172 <Method void AccessibilityRecord.setCurrentItemIndex(int)>
// 4 8:return
}
public void setEnabled(boolean flag)
{
mRecord.setEnabled(flag);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #175 <Method void AccessibilityRecord.setEnabled(boolean)>
// 4 8:return
}
public void setFromIndex(int i)
{
mRecord.setFromIndex(i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #178 <Method void AccessibilityRecord.setFromIndex(int)>
// 4 8:return
}
public void setFullScreen(boolean flag)
{
mRecord.setFullScreen(flag);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #181 <Method void AccessibilityRecord.setFullScreen(boolean)>
// 4 8:return
}
public void setItemCount(int i)
{
mRecord.setItemCount(i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #184 <Method void AccessibilityRecord.setItemCount(int)>
// 4 8:return
}
public void setMaxScrollX(int i)
{
setMaxScrollX(mRecord, i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokestatic #186 <Method void setMaxScrollX(AccessibilityRecord, int)>
// 4 8:return
}
public void setMaxScrollY(int i)
{
setMaxScrollY(mRecord, i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokestatic #188 <Method void setMaxScrollY(AccessibilityRecord, int)>
// 4 8:return
}
public void setParcelableData(Parcelable parcelable)
{
mRecord.setParcelableData(parcelable);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:aload_1
// 3 5:invokevirtual #192 <Method void AccessibilityRecord.setParcelableData(Parcelable)>
// 4 8:return
}
public void setPassword(boolean flag)
{
mRecord.setPassword(flag);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #195 <Method void AccessibilityRecord.setPassword(boolean)>
// 4 8:return
}
public void setRemovedCount(int i)
{
mRecord.setRemovedCount(i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #198 <Method void AccessibilityRecord.setRemovedCount(int)>
// 4 8:return
}
public void setScrollX(int i)
{
mRecord.setScrollX(i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #201 <Method void AccessibilityRecord.setScrollX(int)>
// 4 8:return
}
public void setScrollY(int i)
{
mRecord.setScrollY(i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #204 <Method void AccessibilityRecord.setScrollY(int)>
// 4 8:return
}
public void setScrollable(boolean flag)
{
mRecord.setScrollable(flag);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #207 <Method void AccessibilityRecord.setScrollable(boolean)>
// 4 8:return
}
public void setSource(View view)
{
mRecord.setSource(view);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:aload_1
// 3 5:invokevirtual #210 <Method void AccessibilityRecord.setSource(View)>
// 4 8:return
}
public void setSource(View view, int i)
{
setSource(mRecord, view, i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:aload_1
// 3 5:iload_2
// 4 6:invokestatic #212 <Method void setSource(AccessibilityRecord, View, int)>
// 5 9:return
}
public void setToIndex(int i)
{
mRecord.setToIndex(i);
// 0 0:aload_0
// 1 1:getfield #16 <Field AccessibilityRecord mRecord>
// 2 4:iload_1
// 3 5:invokevirtual #215 <Method void AccessibilityRecord.setToIndex(int)>
// 4 8:return
}
private final AccessibilityRecord mRecord;
}
| 33.888889 | 127 | 0.583138 |
111ab01224fd97021a1e8f5af9ebcb4200827652 | 1,922 | /*
* Copyright 2021 LINE Corporation
*
* LINE Corporation 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:
*
* 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 com.linecorp.armeria.common.util;
import java.util.function.IntSupplier;
import com.linecorp.armeria.client.limit.ConcurrencyLimit;
import com.linecorp.armeria.common.annotation.UnstableApi;
/**
* Supplies a cached value which can be useful for the below case.
*
* <p>- Supplies the maximum number of concurrent active requests dynamically for {@link ConcurrencyLimit}.
* For example:
* <pre>{@code
* class DynamicSupplier extends SettableIntSupplier {
* DynamicSupplier() {
* super(10); //set initial value
* AnyListener<Integer> listener = ...
* listener.addListener(this::set);
* }
* }}</pre>
*/
@UnstableApi
public class SettableIntSupplier implements IntSupplier {
private volatile int value;
/**
* Creates a new instance with the specified {@code initialValue}.
*/
public static <T> SettableIntSupplier of(int initialValue) {
return new SettableIntSupplier(initialValue);
}
protected SettableIntSupplier(int initialValue) {
value = initialValue;
}
/**
* Returns the cached value.
*/
@Override
public final int getAsInt() {
return value;
}
/**
* Caches a value.
*/
public final void set(int value) {
this.value = value;
}
}
| 28.264706 | 107 | 0.693548 |
3574cf875c6284687c10637159ec96a823ade2dc | 595 | package net.minecraft.server;
public class ItemSplashPotion extends ItemPotionThrowable {
public ItemSplashPotion(Item.Info item_info) {
super(item_info);
}
@Override
public InteractionResultWrapper<ItemStack> a(World world, EntityHuman entityhuman, EnumHand enumhand) {
world.playSound((EntityHuman) null, entityhuman.locX(), entityhuman.locY(), entityhuman.locZ(), SoundEffects.ENTITY_SPLASH_POTION_THROW, SoundCategory.PLAYERS, 0.5F, 0.4F / (ItemSplashPotion.RANDOM.nextFloat() * 0.4F + 0.8F));
return super.a(world, entityhuman, enumhand);
}
}
| 39.666667 | 234 | 0.736134 |
b078dbd5e8c3f0bd58a6235d1f197b97e1fb80d7 | 1,311 | package com.google.jenkins.plugins.computeengine.client;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.model.Operation;
import java.io.IOException;
// This class is a collection of things that ought to be in
// com.google.cloud.graphite.platforms.plugin.client.ComputeClient,
// but is missing - at least in the version of the library that we use.
public class ComputeClient2 {
private Compute compute;
public ComputeClient2(Compute compute) {
this.compute = compute;
}
public Operation startInstance(String project, String zone, String name) throws IOException {
Compute.Instances.Start request = compute.instances().start(project, zone, name);
Operation operation = request.execute();
return operation;
}
public Operation stopInstance(String project, String zone, String name) throws IOException {
Compute.Instances.Stop request = compute.instances().stop(project, zone, name);
Operation operation = request.execute();
return operation;
}
public Operation getZoneOperation(String project, String zone, String operation)
throws IOException {
Compute.ZoneOperations.Get request = compute.zoneOperations().get(project, zone, operation);
Operation response = request.execute();
return response;
}
}
| 34.5 | 96 | 0.755912 |
ed345358a712d66a3505a023c8f69aae092e5937 | 4,592 | package org.shapelogic.imageprocessing;
import org.shapelogic.color.ValueAreaFactory;
import org.shapelogic.imageutil.SLImage;
import static org.shapelogic.imageutil.ImageUtil.runPluginFilterOnBufferedImage;
/** Test SBSegment.
* <br />
*
* @author Sami Badawi
*
*/
public class BaseParticleCounterTest extends AbstractImageProcessingTests {
BaseParticleCounter _baseParticleCounter;
@Override
protected void setUp() throws Exception {
super.setUp();
_baseParticleCounter = new BaseParticleCounter();
_dirURL = "./src/test/resources/images/particles";
_fileFormat = ".gif";
}
public void testSpot1Noise5Jpg() {
String fileName = "spot1Noise5";
SLImage bp = runPluginFilterOnBufferedImage(filePath(fileName,".jpg"), _baseParticleCounter);
assertEquals(30,bp.getWidth());
// assertTrue(bp.isInvertedLut());
int pixel = bp.get(0,0);
assertEquals(16382457,pixel); //So this is a white background pixel
ValueAreaFactory factory = _baseParticleCounter.getSegmentation().getSegmentAreaFactory();
assertNotNull(factory);
assertEquals(2,factory.getStore().size());
assertEquals(1,_baseParticleCounter.getParticleCount());
assertTrue(_baseParticleCounter.isParticleImage());
}
public void testShortVerticalGif() {
String fileName = "oneWhitePixelGray";
SLImage bp = runPluginFilterOnBufferedImage(filePath(fileName), _baseParticleCounter);
assertEquals(1,bp.getWidth());
assertTrue(bp.isInvertedLut());
int pixel = bp.get(0,0);
assertEquals(0,pixel); //So this is a white background pixel
ValueAreaFactory factory = _baseParticleCounter.getSegmentation().getSegmentAreaFactory();
assertNotNull(factory);
assertEquals(1,factory.getStore().size());
assertTrue(_baseParticleCounter.isParticleImage());
}
/** This shows that when you save and image as PNG it will always be opened
* as a color image.
*/
public void testShortVerticalPng() {
String fileName = "oneWhitePixelGray";
SLImage bp = runPluginFilterOnBufferedImage(filePath(fileName,".png"), _baseParticleCounter);
assertTrue(bp.isEmpty());
if (true) return;
assertEquals(1,bp.getWidth());
int pixel = bp.get(0,0);
assertEquals(0,pixel);
ValueAreaFactory factory = _baseParticleCounter.getSegmentation().getSegmentAreaFactory();
assertNotNull(factory);
assertEquals(1,factory.getStore().size());
assertTrue(_baseParticleCounter.isParticleImage());
}
public void testBlobsGif() {
String fileName = "blobs";
SLImage bp = runPluginFilterOnBufferedImage(filePath(fileName), _baseParticleCounter);
assertEquals(256,bp.getWidth());
assertEquals(65024,bp.getPixelCount());
int pixel = bp.get(0,0);
assertEquals(40,pixel);
ValueAreaFactory factory = _baseParticleCounter.getSegmentation().getSegmentAreaFactory();
assertNotNull(factory);
assertEquals(67,factory.getStore().size());
assertTrue(_baseParticleCounter.isParticleImage());
assertTrue(bp.isInvertedLut());
}
/** This gets opened as a byte interleaved and not as an int RGB
*/
public void testCleanSpotPng() {
String fileName = "spot1Clean";
SLImage bp = runPluginFilterOnBufferedImage(filePath(fileName,".png"), _baseParticleCounter);
assertEquals(30,bp.getWidth());
assertEquals(900,bp.getPixelCount());
int pixel = bp.get(0,0);
assertEquals(0xffffff,pixel);
ValueAreaFactory factory = _baseParticleCounter.getSegmentation().getSegmentAreaFactory();
assertNotNull(factory);
assertEquals(1,_baseParticleCounter.getParticleCount());
assertEquals(2,factory.getStore().size());
}
public void testSpot1Noise5() {
String fileName = "spot1Noise5";
SLImage bp = runPluginFilterOnBufferedImage(filePath(fileName,".jpg"), _baseParticleCounter);
assertEquals(30,bp.getWidth());
assertEquals(900,bp.getPixelCount());
int pixel = bp.get(0,0);
assertEquals(16382457,pixel);
ValueAreaFactory factory = _baseParticleCounter.getSegmentation().getSegmentAreaFactory();
assertNotNull(factory);
assertEquals(1,_baseParticleCounter.getParticleCount());
assertEquals(2,factory.getStore().size());
}
public void testSpot1Noise10() {
String fileName = "spot1Noise10";
SLImage bp = runPluginFilterOnBufferedImage(filePath(fileName,".jpg"), _baseParticleCounter);
assertEquals(30,bp.getWidth());
assertEquals(900,bp.getPixelCount());
int pixel = bp.get(0,0);
assertEquals(16645629,pixel);
ValueAreaFactory factory = _baseParticleCounter.getSegmentation().getSegmentAreaFactory();
assertNotNull(factory);
assertEquals(1,_baseParticleCounter.getParticleCount());
assertEquals(2,factory.getStore().size());
}
}
| 37.032258 | 96 | 0.762195 |
db23f18a91a8a9f75eaf4d1601351851e1314d93 | 18,897 | package msifeed.mc.more.crabs.combat;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
import msifeed.mc.more.More;
import msifeed.mc.more.crabs.action.Action;
import msifeed.mc.more.crabs.action.ActionRegistry;
import msifeed.mc.more.crabs.action.ActionTag;
import msifeed.mc.more.crabs.action.Combo;
import msifeed.mc.more.crabs.action.effects.Buff;
import msifeed.mc.more.crabs.action.effects.Effect;
import msifeed.mc.more.crabs.rolls.Criticalness;
import msifeed.mc.more.crabs.rolls.Dices;
import msifeed.mc.more.crabs.utils.*;
import msifeed.mc.sys.attributes.MissingRequiredAttributeException;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public enum CombatManager {
INSTANCE;
public void init() {
MinecraftForge.EVENT_BUS.register(this);
FMLCommonHandler.instance().bus().register(this);
}
public boolean doAction(EntityLivingBase self, CombatContext ctx, Action action) {
final boolean actionChanged = ctx.action == null || !ctx.action.id.equals(action.id);
if (ctx.phase == CombatContext.Phase.IDLE) {
if (!action.isOffencive())
return false;
if (actionChanged)
updateAction(self, action);
else if (action.requiresNoRoll())
endAction(self, ctx);
return true;
} else if (ctx.phase == CombatContext.Phase.DEFEND) {
if (ctx.offender == 0)
return false;
final EntityLivingBase offender = GetUtils.entityLiving(self, ctx.offender).orElse(null);
if (offender == null)
return false;
final CombatContext offenderCom = CombatAttribute.require(offender);
if (offenderCom.phase != CombatContext.Phase.WAIT)
return false;
final ActionContext offenderAct = ActionAttribute.require(offender);
if (!action.isValidDefencive(offenderAct.action.getType()))
return false;
if (actionChanged)
updateAction(self, action);
else {
ctx.phase = CombatContext.Phase.WAIT;
if (!tryFinishMove(offender, offenderCom))
CombatAttribute.INSTANCE.set(self, ctx);
}
return true;
}
return false;
}
private static void updateAction(EntityLivingBase self, Action action) {
CombatAttribute.INSTANCE.update(self, com -> com.action = action);
final ActionContext act = ActionAttribute.get(self).orElse(new ActionContext());
act.action = action;
ActionAttribute.INSTANCE.set(self, act);
}
public void endAction(EntityLivingBase self, CombatContext com) {
if (com.action.requiresNoRoll()) {
finishSoloMove(new FighterInfo(self));
} else {
com.phase = CombatContext.Phase.WAIT;
CombatAttribute.INSTANCE.set(self, com);
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onHurtDamage(LivingHurtEvent event) {
if (event.entityLiving.worldObj.isRemote)
return;
try {
final Entity srcEntity = event.source.getEntity();
if (srcEntity instanceof EntityLivingBase)
handleEntityDamage(event, (EntityLivingBase) srcEntity);
else
handleNeutralDamage(event);
} catch (Exception e) {
e.printStackTrace();
}
}
private void handleNeutralDamage(LivingHurtEvent event) {
final EntityLivingBase vicEntity = event.entityLiving;
final CombatContext vicCom = CombatAttribute.get(vicEntity).orElse(null);
if (vicCom == null)
return;
if (vicCom.phase == CombatContext.Phase.END)
return; // Pass full damage
if (vicCom.offender != 0)
return;
final EntityLivingBase srcEntity;
final CombatContext srcCom;
try {
srcEntity = GetUtils.entityLiving(vicEntity, vicCom.offender).orElse(null);
if (srcEntity == null)
return;
srcCom = CombatAttribute.require(srcEntity);
} catch (MissingRequiredAttributeException e) {
return;
}
event.setCanceled(true);
if (srcEntity == vicEntity) // Do not attack your puppet
return;
if (canNotDealDamage(srcCom, vicCom))
return;
vicCom.damageDealt.add(new DamageAmount(event.source, event.ammount));
CombatAttribute.INSTANCE.set(vicEntity, vicCom);
}
private void handleEntityDamage(LivingHurtEvent event, EntityLivingBase damageSrcEntity) {
final EntityLivingBase vicEntity = event.entityLiving;
final CombatContext vicCom = CombatAttribute.get(vicEntity).orElse(null);
if (vicCom == null)
return;
if (vicCom.phase == CombatContext.Phase.END)
return; // Pass full damage
final EntityLivingBase offEntity;
final CombatContext offCom;
try {
final CombatContext directCom = CombatAttribute.require(damageSrcEntity);
if (directCom.puppet != 0) {
final EntityLivingBase puppet = GetUtils.entityLiving(damageSrcEntity, directCom.puppet).orElse(null);
if (puppet == null)
return;
offEntity = puppet;
offCom = CombatAttribute.require(puppet);
} else {
offEntity = damageSrcEntity;
offCom = directCom;
}
} catch (MissingRequiredAttributeException e) {
return;
}
event.setCanceled(true);
if (offEntity == vicEntity) // Do not attack your puppet
return;
if (canNotDealDamage(offCom, vicCom))
return;
boolean shouldUpdateOffender = false;
if (offCom.phase != CombatContext.Phase.ATTACK) {
offCom.role = CombatContext.Role.OFFENCE;
offCom.phase = CombatContext.Phase.ATTACK;
offCom.defenders = new ArrayList<>();
shouldUpdateOffender = true;
}
if (!offCom.defenders.contains(vicEntity.getEntityId())) {
offCom.defenders.add(vicEntity.getEntityId());
shouldUpdateOffender = true;
}
if (shouldUpdateOffender)
CombatAttribute.INSTANCE.set(offEntity, offCom);
if (vicCom.phase != CombatContext.Phase.DEFEND) {
CombatAttribute.INSTANCE.update(vicEntity, context -> {
context.role = CombatContext.Role.DEFENCE;
context.phase = CombatContext.Phase.DEFEND;
context.offender = offEntity.getEntityId();
});
}
final float fistsMod;
if (offEntity.getHeldItem() == null)
fistsMod = CharacterAttribute.get(offEntity).map(c -> c.fistsDamage).orElse(0);
else
fistsMod = 0;
final float modMod = MetaAttribute.get(offEntity).map(m -> m.modifiers.damage).orElse(0);
final float finalDamage = event.ammount + fistsMod + modMod;
if (finalDamage <= 0)
return;
vicCom.damageDealt.add(new DamageAmount(event.source, finalDamage));
CombatAttribute.INSTANCE.set(vicEntity, vicCom);
}
private boolean canNotDealDamage(CombatContext srcCom, CombatContext vicCom) {
if (srcCom.isTraining() != vicCom.isTraining())
return true; // Ignore if someone is not in training
if (srcCom.phase != CombatContext.Phase.IDLE && srcCom.phase != CombatContext.Phase.ATTACK)
return true;
if (srcCom.action == null)
return true;
if (vicCom.phase != CombatContext.Phase.IDLE && vicCom.phase != CombatContext.Phase.DEFEND)
return true;
return false;
}
private boolean tryFinishMove(EntityLivingBase offender, CombatContext offenderCom) {
final List<EntityLivingBase> defenderEntities = offenderCom.defenders.stream()
.map(id -> GetUtils.entityLiving(offender, id).orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.toList());
final List<CombatContext> defenderComs = defenderEntities.stream()
.map(CombatAttribute::require)
.collect(Collectors.toList());
final boolean allDefendersAreWaiting = defenderComs.stream()
.allMatch(ctx -> ctx.phase == CombatContext.Phase.WAIT);
final boolean everyoneIsReady = defenderEntities.size() == defenderComs.size() && allDefendersAreWaiting;
if (!everyoneIsReady)
return false;
finishMove(offender, defenderEntities);
return true;
}
private void finishMove(EntityLivingBase offenderEntity, List<EntityLivingBase> defenderEntities) {
final FighterInfo offender = new FighterInfo(offenderEntity);
final List<FighterInfo> defenders = defenderEntities.stream().map(FighterInfo::new).collect(Collectors.toList());
offender.com.phase = CombatContext.Phase.END;
for (FighterInfo defender : defenders)
defender.com.phase = CombatContext.Phase.END;
applyScores(offender);
for (FighterInfo defender : defenders) {
do {
applyScores(defender);
} while (offender.act.compareTo(defender.act) == 0);
}
for (FighterInfo defender : defenders) {
if (offender.act.compareTo(defender.act) > 0)
applyEffectsAndResults(offender, defender);
else
applyEffectsAndResults(defender, offender);
}
cleanupMove(offender);
for (FighterInfo defender : defenders)
cleanupMove(defender);
CombatAttribute.INSTANCE.set(offender.entity(), offender.com);
for (FighterInfo defender : defenders)
CombatAttribute.INSTANCE.set(defender.entity(), defender.com);
}
private static void applyScores(FighterInfo self) {
if (self.act.action.requiresNoRoll())
return;
self.act.resetScore();
self.act.scorePlayerMod = self.mod.roll;
self.act.critical = Dices.critical();
if (self.act.critical == Criticalness.FAIL)
self.act.successful = false;
applyBuffs(self.com.buffs, Effect.Stage.PRE_SCORE, self, null);
applyEffects(self.passiveEffects(), Effect.Stage.PRE_SCORE, self, null);
applyEffects(self.act.action.self, Effect.Stage.SCORE, self, null);
applyBuffs(self.com.buffs, Effect.Stage.SCORE, self, null);
applyEffects(self.passiveEffects(), Effect.Stage.SCORE, self, null);
}
private static void applyEffectsAndResults(FighterInfo winner, FighterInfo looser) {
applyEffects(winner.act.action.self, Effect.Stage.ACTION, winner, looser);
applyEffects(winner.act.action.target, Effect.Stage.ACTION, looser, winner);
applyBuffs(winner.com.buffs, Effect.Stage.ACTION, winner, looser);
applyBuffs(looser.com.buffs, Effect.Stage.ACTION, looser, winner);
applyEffects(winner.passiveEffects(), Effect.Stage.ACTION, winner, looser);
applyEffects(looser.passiveEffects(), Effect.Stage.ACTION, looser, winner);
if (winner.act.action.isOffencive() && !winner.act.action.requiresNoRoll()) {
final Combo.ComboLookup combo = Combo.find(ActionRegistry.getCombos(), winner.com.prevActions, winner.act.action.id);
if (combo != null) {
winner.com.prevActions.removeAll(combo.match);
winner.comboAction = combo.c.action;
applyEffects(combo.c.action.self, Effect.Stage.ACTION, winner, looser);
applyEffects(combo.c.action.target, Effect.Stage.ACTION, looser, winner);
} else {
winner.com.prevActions.add(winner.act.action.id);
}
}
applyActionResults(winner);
applyActionResults(looser);
CombatNotifications.actionResult(winner, looser);
}
private void finishSoloMove(FighterInfo self) {
self.com.phase = CombatContext.Phase.END;
if (self.act.action.hasAnyTag(ActionTag.apply)) {
final EntityLivingBase entity = self.entity();
final ItemStack heldItem = entity.getHeldItem();
if (heldItem != null && heldItem.stackSize > 0) {
final List<Buff> newBuffs = PotionsHandler.convertItemStack(heldItem, entity);
if (!newBuffs.isEmpty()) {
self.act.buffsToReceive.addAll(newBuffs);
heldItem.stackSize--;
if (heldItem.stackSize == 0 && entity instanceof EntityPlayer) {
final EntityPlayer player = ((EntityPlayer) entity);
player.inventory.mainInventory[player.inventory.currentItem] = null;
player.inventory.markDirty();
MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, heldItem));
}
}
}
}
applyEffects(self.act.action.self, Effect.Stage.ACTION, self, null);
applyBuffs(self.com.buffs, Effect.Stage.ACTION, self, null);
applyEffects(self.passiveEffects(), Effect.Stage.ACTION, self, null);
applyActionResults(self);
CombatNotifications.soloMoveResult(self);
cleanupMove(self);
CombatAttribute.INSTANCE.set(self.entity(), self.com);
}
private static void cleanupMove(FighterInfo self) {
self.com.removeEndedEffects();
self.com.softReset();
ActionAttribute.remove(self.entity());
}
private static void applyBuffs(List<Buff> buffs, Effect.Stage stage, FighterInfo self, FighterInfo other) {
for (Buff b : buffs)
if (b.shouldApply(stage, self, other))
b.applyEffect(stage, self, other);
}
private static void applyEffects(List<Effect> effects, Effect.Stage stage, FighterInfo self, FighterInfo other) {
for (Effect e : effects)
if (e.shouldApply(stage, self, other))
e.apply(stage, self, other);
}
private static void applyActionResults(FighterInfo self) {
final EntityLivingBase selfEntity = self.entity();
final CombatDefines.DamageSettings damageSettings = More.DEFINES.combat().damageSettings;
final int armorAmount = self.chr.armor > 0 ? self.chr.armor : selfEntity.getTotalArmorValue();
final int MIN_DAMAGE = 1;
float totalDamage = 0;
for (DamageAmount da : self.com.damageToReceive) {
totalDamage += da.piecing
? da.amount
: damageSettings.applyArmor(da.amount, armorAmount, self.chr.damageThreshold);
}
if (selfEntity instanceof EntityPlayer)
((EntityPlayer) selfEntity).inventory.damageArmor(totalDamage);
if (totalDamage > MIN_DAMAGE)
self.com.prevActions.clear();
for (Buff buff : self.act.buffsToReceive)
Buff.mergeBuff(self.com.buffs, buff);
final boolean deadlyAttack = totalDamage > 0 && selfEntity.getHealth() - totalDamage <= MIN_DAMAGE;
final float currentHealth = selfEntity.getHealth();
final float newHealth;
if (deadlyAttack) {
if (self.com.knockedOut) {
newHealth = self.com.isTraining()
? self.com.healthBeforeJoin
: 0;
self.com.knockedOut = false;
CombatNotifications.notifyKilled(self);
} else {
newHealth = MIN_DAMAGE;
self.com.knockedOut = true;
CombatNotifications.notifyKnockedOut(self);
}
} else if (totalDamage >= MIN_DAMAGE) {
newHealth = currentHealth - totalDamage;
} else {
newHealth = currentHealth;
}
if (newHealth != currentHealth) {
selfEntity.setHealth(newHealth);
selfEntity.attackEntityFrom(DamageSource.generic, 0); // Visual damage
if (newHealth <= 0)
selfEntity.onDeath(new DamageSource("CRAbS"));
}
}
@SubscribeEvent
public void onLivingJoinWorld(EntityJoinWorldEvent event) {
if (event.entity.worldObj.isRemote || !(event.entity instanceof EntityLivingBase))
return;
CombatAttribute.get((EntityLivingBase) event.entity)
.filter(com -> com.phase.isInCombat())
.ifPresent(com -> resetCombatantWithRelatives((EntityLivingBase) event.entity));
}
@SubscribeEvent
public void onPlayerLogOut(PlayerEvent.PlayerLoggedOutEvent event) {
if (event.player.worldObj.isRemote)
return;
resetCombatantWithRelatives(event.player);
}
public void joinCombat(EntityLivingBase target, CombatContext com) {
com.phase = CombatContext.Phase.IDLE;
CombatAttribute.INSTANCE.set(target, com);
ActionAttribute.remove(target);
}
public void removeFromCombat(EntityLivingBase entity, CombatContext com) {
resetCombatantWithRelatives(entity);
if (com.isTraining())
entity.setHealth(com.healthBeforeJoin);
com.hardReset();
CombatAttribute.INSTANCE.set(entity, com);
ActionAttribute.remove(entity);
}
public static void resetCombatantWithRelatives(EntityLivingBase entity) {
final CombatContext com = CombatAttribute.get(entity).orElse(null);
if (com == null)
return;
final Stream<Integer> relatives = Stream.concat(Stream.of(com.offender), com.defenders.stream());
ActionAttribute.remove(entity);
CombatAttribute.INSTANCE.update(entity, CombatContext::softReset);
relatives.map(id -> GetUtils.entityLiving(entity, id))
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(CombatManager::resetCombatantWithRelatives);
}
}
| 39.286902 | 129 | 0.632428 |
902e06d8947be86f39c69d4f2f4b04fa9d6c83a5 | 1,900 | /*
* Copyright 2017 The Mifos Initiative.
*
* 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 io.mifos.portfolio.service.internal.service;
import io.mifos.portfolio.api.v1.domain.ChargeDefinition;
import io.mifos.portfolio.service.internal.mapper.ChargeDefinitionMapper;
import io.mifos.portfolio.service.internal.repository.ChargeDefinitionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.stream.Stream;
/**
* @author Myrle Krantz
*/
@Service
public class ConfigurableChargeDefinitionService {
private final ChargeDefinitionRepository chargeDefinitionRepository;
@Autowired
public ConfigurableChargeDefinitionService(final ChargeDefinitionRepository chargeDefinitionRepository) {
this.chargeDefinitionRepository = chargeDefinitionRepository;
}
public Stream<ChargeDefinition> findAllEntities(final String productIdentifier) {
return chargeDefinitionRepository.findByProductId(productIdentifier)
.map(ChargeDefinitionMapper::map);
}
public Optional<ChargeDefinition> findByIdentifier(final String productIdentifier, final String identifier) {
return chargeDefinitionRepository
.findByProductIdAndChargeDefinitionIdentifier(productIdentifier, identifier)
.map(ChargeDefinitionMapper::map);
}
}
| 38 | 111 | 0.794211 |
9292ae7cb7894a26272c9876e83ba625b59ce2de | 4,506 | package mod.noobulus.tetrapak.quark;
import mod.noobulus.tetrapak.TetraPak;
import net.minecraft.block.material.MaterialColor;
import net.minecraft.util.ResourceLocation;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;
import static net.minecraft.block.material.MaterialColor.*;
public final class CorundumMap {
public static final Map<MaterialColor, Integer> COLOR_MAP = new HashMap<>();
public static final Map<Integer, ResourceLocation> CRYSTAL_MAP = new HashMap<>();
public static final Map<Integer, String> NAME_MAP = new HashMap<>();
private static final int RED = 1;
private static final int ORANGE = 2;
private static final int YELLOW = 3;
private static final int GREEN = 4;
private static final int BLUE = 5;
private static final int INDIGO = 6;
private static final int VIOLET = 7;
private static final int WHITE = 8;
private static final int BLACK = 9;
static {
COLOR_MAP.put(NONE, BLACK);
COLOR_MAP.put(GRASS, GREEN);
COLOR_MAP.put(SAND, YELLOW);
COLOR_MAP.put(WOOL, WHITE);
COLOR_MAP.put(FIRE, RED);
COLOR_MAP.put(ICE, INDIGO);
COLOR_MAP.put(METAL, WHITE);
COLOR_MAP.put(PLANT, GREEN);
COLOR_MAP.put(SNOW, WHITE);
COLOR_MAP.put(CLAY, WHITE);
COLOR_MAP.put(DIRT, ORANGE);
COLOR_MAP.put(STONE, BLACK);
COLOR_MAP.put(WATER, BLUE);
COLOR_MAP.put(WOOD, ORANGE);
COLOR_MAP.put(QUARTZ, WHITE);
COLOR_MAP.put(COLOR_ORANGE, ORANGE);
COLOR_MAP.put(COLOR_MAGENTA, INDIGO);
COLOR_MAP.put(COLOR_LIGHT_BLUE, BLUE);
COLOR_MAP.put(COLOR_YELLOW, YELLOW);
COLOR_MAP.put(COLOR_LIGHT_GREEN, GREEN);
COLOR_MAP.put(COLOR_PINK, VIOLET);
COLOR_MAP.put(COLOR_GRAY, BLACK);
COLOR_MAP.put(COLOR_LIGHT_GRAY, WHITE);
COLOR_MAP.put(COLOR_CYAN, BLUE);
COLOR_MAP.put(COLOR_PURPLE, INDIGO);
COLOR_MAP.put(COLOR_BLUE, BLUE);
COLOR_MAP.put(COLOR_BROWN, ORANGE);
COLOR_MAP.put(COLOR_GREEN, GREEN);
COLOR_MAP.put(COLOR_RED, RED);
COLOR_MAP.put(COLOR_BLACK, BLACK);
COLOR_MAP.put(GOLD, YELLOW);
COLOR_MAP.put(DIAMOND, BLUE);
COLOR_MAP.put(LAPIS, BLUE);
COLOR_MAP.put(EMERALD, GREEN);
COLOR_MAP.put(PODZOL, ORANGE);
COLOR_MAP.put(NETHER, RED);
COLOR_MAP.put(TERRACOTTA_WHITE, WHITE);
COLOR_MAP.put(TERRACOTTA_ORANGE, ORANGE);
COLOR_MAP.put(TERRACOTTA_MAGENTA, INDIGO);
COLOR_MAP.put(TERRACOTTA_LIGHT_BLUE, BLUE);
COLOR_MAP.put(TERRACOTTA_YELLOW, YELLOW);
COLOR_MAP.put(TERRACOTTA_LIGHT_GREEN, GREEN);
COLOR_MAP.put(TERRACOTTA_PINK, VIOLET);
COLOR_MAP.put(TERRACOTTA_GRAY, BLACK);
COLOR_MAP.put(TERRACOTTA_LIGHT_GRAY, WHITE);
COLOR_MAP.put(TERRACOTTA_CYAN, BLUE);
COLOR_MAP.put(TERRACOTTA_PURPLE, INDIGO);
COLOR_MAP.put(TERRACOTTA_BLUE, BLUE);
COLOR_MAP.put(TERRACOTTA_BROWN, ORANGE);
COLOR_MAP.put(TERRACOTTA_GREEN, GREEN);
COLOR_MAP.put(TERRACOTTA_RED, RED);
COLOR_MAP.put(TERRACOTTA_BLACK, BLACK);
COLOR_MAP.put(CRIMSON_NYLIUM, RED);
COLOR_MAP.put(CRIMSON_STEM, RED);
COLOR_MAP.put(CRIMSON_HYPHAE, RED);
COLOR_MAP.put(WARPED_NYLIUM, BLUE);
COLOR_MAP.put(WARPED_STEM, BLUE);
COLOR_MAP.put(WARPED_HYPHAE, BLUE);
COLOR_MAP.put(WARPED_WART_BLOCK, BLUE);
CRYSTAL_MAP.put(RED, asQuarkCrystal("red"));
CRYSTAL_MAP.put(ORANGE, asQuarkCrystal("orange"));
CRYSTAL_MAP.put(YELLOW, asQuarkCrystal("yellow"));
CRYSTAL_MAP.put(GREEN, asQuarkCrystal("green"));
CRYSTAL_MAP.put(BLUE, asQuarkCrystal("blue"));
CRYSTAL_MAP.put(INDIGO, asQuarkCrystal("indigo"));
CRYSTAL_MAP.put(VIOLET, asQuarkCrystal("violet"));
CRYSTAL_MAP.put(WHITE, asQuarkCrystal("white"));
CRYSTAL_MAP.put(BLACK, asQuarkCrystal("black"));
NAME_MAP.put(RED, "red");
NAME_MAP.put(ORANGE, "orange");
NAME_MAP.put(YELLOW, "yellow");
NAME_MAP.put(GREEN, "green");
NAME_MAP.put(BLUE, "blue");
NAME_MAP.put(INDIGO, "indigo");
NAME_MAP.put(VIOLET, "violet");
NAME_MAP.put(WHITE, "white");
NAME_MAP.put(BLACK, "black");
}
private CorundumMap() {
}
private static ResourceLocation asQuarkCrystal(String color) {
return new ResourceLocation("quark", color + "_crystal_cluster");
}
public static void checkMappings() {
TetraPak.LOGGER.info("Checking corundum color mappings...");
Arrays.stream(MATERIAL_COLORS)
.filter(((Predicate<MaterialColor>) COLOR_MAP::containsKey).negate())
.filter(Objects::nonNull)
.forEach(materialColor -> TetraPak.LOGGER.error("Material color {} of id {} and colour {} was not mapped to a corundum variant",
materialColor, materialColor.id, materialColor.col));
}
}
| 34.930233 | 131 | 0.748114 |
0e1cafc575c2ee5b2e02baa44524e7f6ac6e20b6 | 1,275 | package com.eon.androidthings.sensehatdriverlibrary.devices.fonts;
import android.content.res.AssetManager;
/**
* TODO Description
*/
public class BlackWhiteFont extends AbstractLEDFont {
private static final String FONT_IMAGE = "BlackWhiteFont.png";
// ----------------------------------------------------- Instance Variables
private static final String FONT_LETTERS = " ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖÉÜabcdefghijklmnopqrstuvwxyzåäöéü0123456789.,?!\"#$%&-+*:;/\\<>()'`=";
// ------------------------------------------------------------ Constructor
public BlackWhiteFont(AssetManager assetManager) {
super(assetManager);
}
// --------------------------------------------------------- Public Methods
@Override
public String getFontImageResourceName() {
return FONT_IMAGE;
}
@Override
public String getFontLetters() {
return FONT_LETTERS;
}
protected int enhancePixelColor(int x, int y, int currentColor) {
String colorAsHex = Integer.toHexString(currentColor);
// currentColor = currentColor | 16777215; // white
currentColor = currentColor | 255; // blue
String colorAsHex2 = Integer.toHexString(currentColor);
return currentColor;
}
}
| 29.651163 | 148 | 0.596078 |
70c7ba7ad7dce7165ceb94cd090fe2bfba0dc3da | 2,713 | package com.nonstoppvp.core.utils;
import com.google.common.collect.Maps;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.enchantments.EnchantmentTarget;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class EnchantUtils
{
private Map<String, Enchantment> enchantments = Maps.newHashMap();
private Enchantment fakeEnchant;
public void createEnchant()
{
fakeEnchant = new FakeEnchant(100);
enchantments.put("fake", fakeEnchant);
try
{
Field f = Enchantment.class.getDeclaredField("acceptingNew");
f.setAccessible(true);
f.set(null, true);
Enchantment.registerEnchantment(fakeEnchant);
} catch (Exception e)
{
e.printStackTrace();
}
}
public void handleShutdown()
{
try
{
Field byIdField = Enchantment.class.getDeclaredField("byId");
Field byNameField = Enchantment.class.getDeclaredField("byName");
byIdField.setAccessible(true);
byNameField.setAccessible(true);
HashMap<Integer, Enchantment> byId = (HashMap<Integer, Enchantment>) byIdField.get(null);
HashMap<Integer, Enchantment> byName = (HashMap<Integer, Enchantment>) byNameField.get(null);
for (Enchantment e : enchantments.values())
{
if (byId.containsKey(e.getId()))
byId.remove(e.getId());
if (byName.containsKey(e.getName()))
byName.remove(e.getName());
}
} catch (Exception ignored)
{
}
}
public class FakeEnchant extends Enchantment
{
public FakeEnchant(int id)
{
super(id);
}
@Override
public String getName()
{
return null;
}
@Override
public int getMaxLevel()
{
return 0;
}
@Override
public int getStartLevel()
{
return 0;
}
@Override
public EnchantmentTarget getItemTarget()
{
return null;
}
@Override
public boolean isTreasure()
{
return false;
}
@Override
public boolean isCursed()
{
return false;
}
@Override
public boolean conflictsWith(Enchantment enchantment)
{
return false;
}
@Override
public boolean canEnchantItem(ItemStack itemStack)
{
return false;
}
}
}
| 23.188034 | 105 | 0.55105 |
f074e1a8581c31576e39352b9d8bf40c805d3ef3 | 374 | package com.epam.pricecheckercore.model.product;
import com.epam.pricecheckercore.model.magazine.Magazine;
import org.javamoney.moneta.Money;
import org.jsoup.nodes.Document;
public interface Product {
Magazine getMagazine();
boolean isInStock(Document document);
Money getDiscountedPrice(Document document);
Money getNormalPrice(Document document);
}
| 22 | 57 | 0.78877 |
2e7fc2cd2f0dd7571cc94b5f331adfe920b8728a | 3,057 | package com.webank.wedatasphere.streamis.appconn.standard;
import com.webank.wedatasphere.dss.appconn.core.AppConn;
import com.webank.wedatasphere.dss.standard.app.structure.StructureIntegrationStandard;
import com.webank.wedatasphere.dss.standard.app.structure.project.ProjectService;
import com.webank.wedatasphere.dss.standard.app.structure.role.RoleService;
import com.webank.wedatasphere.dss.standard.app.structure.status.AppStatusService;
import com.webank.wedatasphere.dss.standard.common.desc.AppDesc;
import com.webank.wedatasphere.streamis.appconn.service.StreamisProjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class StreamisStructureIntegrationStandard implements StructureIntegrationStandard {
private static final Logger LOGGER = LoggerFactory.getLogger(StreamisStructureIntegrationStandard.class);
private ProjectService projectService;
private AppConn appConn;
private static StreamisStructureIntegrationStandard instance;
private AppDesc appDesc;
private static final String NAME = "StreamisStructureIntegrationStandard";
private StreamisStructureIntegrationStandard(AppConn appConn){
this.appConn = appConn;
init();
}
public static StreamisStructureIntegrationStandard getInstance(AppConn appConn){
if (null == instance){
synchronized (StreamisStructureIntegrationStandard.class){
if (null == instance){
instance = new StreamisStructureIntegrationStandard(appConn);
}
}
}
return instance;
}
@Override
public void init() {
this.projectService = new StreamisProjectService(this.appConn);
this.projectService.setAppDesc(getAppDesc());
}
@Override
public RoleService getRoleService() {
LOGGER.warn("yet no role service implemented for streamis appconn, will return null");
return null;
}
@Override
public ProjectService getProjectService() {
if (null == projectService){
LOGGER.error("project Service in streamis is null");
return null;
}
return this.projectService;
}
@Override
public AppStatusService getAppStateService() {
LOGGER.warn("AppStatus Service not supported in streamis yet");
return null;
}
@Override
public AppDesc getAppDesc() {
if (appConn == null){
LOGGER.error("appconn in streamis is null, so appDesc is null too");
return null;
}
return this.appConn.getAppDesc();
}
@Override
public void setAppDesc(AppDesc appDesc) {
//to noting
this.appDesc = appDesc;
}
@Override
public void close() throws IOException {
}
@Override
public String getStandardName() {
return NAME;
}
@Override
public int getGrade() {
return 0;
}
@Override
public boolean isNecessary() {
return false;
}
}
| 27.053097 | 109 | 0.686948 |
e61a2bbc66ecaa196d90aeb581affd7ce45dac8d | 432 | package com.ocadotechnology.newrelic.alertsconfigurator.configuration.condition.violationclosetimer;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public enum ViolationCloseTimer {
DURATION_1("1"),
DURATION_2("2"),
DURATION_4("4"),
DURATION_8("8"),
DURATION_12("12"),
DURATION_24("24");
String duration;
}
| 22.736842 | 100 | 0.75 |
d95eee9c944f6fd083d834503259c886b34143a3 | 49,643 | /*
* Copyright 2016 The Sem Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thesemproject.opensem.gui.utils;
import java.awt.Color;
import org.thesemproject.opensem.utils.ParallelProcessor;
import org.thesemproject.opensem.classification.ClassificationPath;
import org.thesemproject.opensem.classification.MyAnalyzer;
import org.thesemproject.opensem.classification.Tokenizer;
import org.thesemproject.opensem.gui.SemDocument;
import org.thesemproject.opensem.gui.LogGui;
import org.thesemproject.opensem.gui.SemGui;
import org.thesemproject.opensem.gui.process.ReadExcelToTable;
import org.thesemproject.opensem.gui.process.ReadFolderToTable;
import org.thesemproject.opensem.segmentation.SegmentConfiguration;
import org.thesemproject.opensem.gui.process.SegmentationExcelWriter;
import org.thesemproject.opensem.segmentation.SegmentationResults;
import org.thesemproject.opensem.segmentation.SegmentationUtils;
import org.thesemproject.opensem.tagcloud.TagCloudResults;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import org.mcavallo.opencloud.Cloud;
import org.mcavallo.opencloud.Tag;
import org.thesemproject.opensem.tagcloud.TagClass;
/**
*
* Gestisce gli eventi legate alla tabella dei files e dei segmenti
*/
public class FilesAndSegmentsUtils {
/**
* Gestisce la cancellazione da tabella
*
* @param semGui frame
*/
public static void filesTableDelete(SemGui semGui) {
DefaultTableModel model = (DefaultTableModel) semGui.getFilesTable().getModel();
DefaultTableModel segModel = (DefaultTableModel) semGui.getSegmentsTable().getModel();
int[] rows = semGui.getFilesTable().getSelectedRows();
Set<String> segToDelete = new HashSet<>();
for (int i = 0; i < rows.length; i++) {
int pos = semGui.getFilesTable().convertRowIndexToModel(rows[i] - i);
Integer id = (Integer) model.getValueAt(pos, 0);
SemDocument dto = semGui.getTableData().get(id);
List<Object[]> sr = dto.getSegmentRows();
for (Object[] s : sr) {
segToDelete.add((String) s[0]);
}
semGui.getTableData().remove(id);
model.removeRow(pos);
}
int rc = segModel.getRowCount();
for (int i = rc - 1; i >= 0; i--) {
if (segToDelete.contains(segModel.getValueAt(i, 0))) {
segModel.removeRow(i);
}
}
semGui.updateStats();
}
/**
* Gestisce l'evidenziazione del segmento
*
* @param semGui frame
* @param modifier tipo marcatura
*/
public static void segmentsTableHilightSegment(SemGui semGui, String modifier) {
DefaultTableModel segModel = (DefaultTableModel) semGui.getSegmentsTable().getModel();
int[] rows = semGui.getSegmentsTable().getSelectedRows();
for (int i = 0; i < rows.length; i++) {
//int pos = semGui.getSegmentsTable().convertRowIndexToModel(rows[i]);
semGui.getSegmentsTable().setValueAt(modifier, rows[i], 6);
String seg = (String) semGui.getSegmentsTable().getValueAt(rows[i], 0);
int id = Integer.parseInt(seg.substring(0, seg.indexOf(".")));
SemDocument dto = semGui.getTableData().get(id);
if (dto != null) {
//dto.udpateSegmentsRows(seg);
List<Object[]> rowsS = dto.getSegmentRows();
for (Object[] rowS : rowsS) {
String idS = (String) rowS[0];
if (idS.equals(seg)) {
rowS[6] = modifier;
}
}
dto.setSegmentRows(rowsS);
}
}
}
/**
* Gestisce gli eventi sulla tabella fiels
*
* @param evt eventi
* @param semGui frame
*/
public static void filesTableEventsManagement(MouseEvent evt, SemGui semGui) {
int currentFilesPosition = semGui.getFilesTable().getSelectedRow();
int id = (Integer) semGui.getFilesTable().getValueAt(currentFilesPosition, 0);
String text = semGui.getFilesTable().getValueAt(currentFilesPosition, 8).toString();
if (text != null) {
semGui.getFileText().setText(text.replace("\n\n", "\n"));
semGui.getFileText().setCaretPosition(0);
semGui.getFileText1().setText(text.replace("\n\n", "\n"));
semGui.getFileText1().setCaretPosition(0);
}
Object cx = semGui.getFilesTable().getValueAt(currentFilesPosition, 9);
if (cx == null) {
cx = "";
}
String formatted = cx.toString();
if (formatted != null) {
semGui.getFilesPanelHtmlFormatted().setText(formatted);
semGui.getFilesPanelHtmlFormatted().setCaretPosition(0);
semGui.getFilesPanelHtmlFormatted1().setText(formatted);
semGui.getFilesPanelHtmlFormatted1().setCaretPosition(0);
}
SemDocument dto = semGui.getTableData().get(id);
if (dto == null) {
return;
}
if (dto != null && dto.getIdentifiedSegments() != null) {
Map<SegmentConfiguration, List<SegmentationResults>> identifiedSegments = dto.getIdentifiedSegments();
String language = dto.getLanguage();
try {
semGui.getFilesPanelSegmentTree().setModel(new DefaultTreeModel(SegmentationUtils.getJTree(new DefaultMutableTreeNode("Segmentazione"), identifiedSegments, language)));
} catch (Exception e) {
LogGui.printException(e);
}
DefaultTableModel dm = (DefaultTableModel) semGui.getFilesPanleCapturesTable().getModel();
int rowCount = dm.getRowCount();
for (int i = rowCount - 1; i >= 0; i--) {
dm.removeRow(i);
}
dto.getCapturesRows().stream().forEach((Object[] row) -> {
dm.addRow(row);
});
String html;
try {
html = SegmentationUtils.getHtml(dto.getIdentifiedSegments(), language);
} catch (Exception ex) {
html = "";
}
semGui.getFilesPanelHtml().setContentType("text/html");
semGui.getFilesPanelHtml().setText(html);
semGui.getFilesPanelHtml().setCaretPosition(0);
semGui.getFilesPanelHtml1().setContentType("text/html");
semGui.getFilesPanelHtml1().setText(html);
semGui.getFilesPanelHtml1().setCaretPosition(0);
} else {
semGui.getFilesPanelSegmentTree().setModel(new DefaultTreeModel(new DefaultMutableTreeNode("Segmentazione non effettuata")));
semGui.getFilesPanelHtml().setContentType("text/html");
semGui.getFilesPanelHtml().setText("");
semGui.getFilesPanelHtml1().setContentType("text/html");
semGui.getFilesPanelHtml1().setText("");
DefaultTableModel dm = (DefaultTableModel) semGui.getFilesPanleCapturesTable().getModel();
int rowCount = dm.getRowCount();
for (int i = rowCount - 1; i >= 0; i--) {
dm.removeRow(i);
}
}
if (evt != null) {
if (evt.getClickCount() == 2 && !evt.isConsumed()) {
evt.consume();
semGui.doDocumentSegmentation(text, id, currentFilesPosition);
}
}
}
/**
* Gestisce l'evento sulla segment table
*
* @param evt event
* @param semGui frame
* @throws NumberFormatException eccezione sui valori numerici
*/
public static void segmentsTableMouseEventManagement(MouseEvent evt, SemGui semGui) throws NumberFormatException {
final int currentFilesPosition = semGui.getSegmentsTable().getSelectedRow();
String sid = (String) semGui.getSegmentsTable().getValueAt(currentFilesPosition, 0);
int id = Integer.parseInt(sid.substring(0, sid.indexOf(".")));
String text = semGui.getSegmentsTable().getValueAt(currentFilesPosition, 4).toString();
if (text != null) {
semGui.getSegmentText().setText(text.replace("\n\n", "\n"));
semGui.getSegmentText().setCaretPosition(0);
semGui.getTesto().setText(text);
semGui.getTesto().setCaretPosition(0);
semGui.getSegmentTokens().setText(semGui.getME().tokenize(text, semGui.getSegmentsTable().getValueAt(currentFilesPosition, 3).toString()));
semGui.getSegmentTokens().setCaretPosition(0);
} else {
semGui.getTesto().setText("");
semGui.getSegmentText().setText("");
semGui.getSegmentTokens().setText("");
semGui.getImagesPanel().removeAll();
}
DefaultMutableTreeNode clResults = new DefaultMutableTreeNode("Classificazione");
final SemDocument dto = semGui.getTableData().get(id);
if (dto.getIdentifiedSegments() != null) {
List<ClassificationPath> bayes = dto.getClassPath(sid);
if (evt != null) {
if (evt.getClickCount() == 2 && !evt.isConsumed()) {
evt.consume();
if (semGui.isNeedUpdate()) {
semGui.getRebuildIndex().setSelected(true);
semGui.initializeModel();
semGui.setNeedUpdate(false);
}
bayes = semGui.getME().bayesClassify(text, semGui.getSegmentsTable().getValueAt(currentFilesPosition, 3).toString());
dto.setClassPath(sid, bayes);
String newClass1 = "";
String newClass2 = "";
if (bayes.size() == 1) {
newClass1 = bayes.get(0).toSmallClassString();
} else if (bayes.size() >= 2) {
newClass1 = bayes.get(0).toSmallClassString();
newClass2 = bayes.get(1).toSmallClassString();
}
semGui.getSegmentsTable().setValueAt(newClass1, currentFilesPosition, 1);
semGui.getSegmentsTable().setValueAt(newClass2, currentFilesPosition, 2);
}
}
bayes.stream().forEach((ClassificationPath cp) -> {
DefaultMutableTreeNode treeNode1 = new DefaultMutableTreeNode(cp.getTechnology());
DefaultMutableTreeNode currentNode = treeNode1;
for (int i = 0; i < ClassificationPath.MAX_DEEP; i++) {
String node = cp.getPath()[i];
if (node != null) {
String label = node + "(" + ClassificationPath.df.format(cp.getScore()[i]) + ")";
DefaultMutableTreeNode treeNode2 = new DefaultMutableTreeNode(label);
currentNode.add(treeNode2);
currentNode = treeNode2;
}
}
clResults.add(treeNode1);
});
}
semGui.getSegmentClassificationResult().setModel(new DefaultTreeModel(clResults));
GuiUtils.expandAll(semGui.getSegmentClassificationResult());
}
/**
* filtra la tabella dei segmenti sui segmenti classificati sul primo
* livello
*
* @param semGui frame
* @param level livello
*/
public static void segmentsTableFilterOnFirstLevel(SemGui semGui, int level) {
TableRowSorter<TableModel> sorter = (TableRowSorter<TableModel>) semGui.getSegmentsTable().getRowSorter();
sorter.setRowFilter(new RowFilter() {
@Override
public boolean include(RowFilter.Entry entry) {
String idSeg = (String) entry.getValue(0);
Integer id = Integer.parseInt(idSeg.substring(0, idSeg.indexOf(".")));
SemDocument dto = semGui.getTableData().get(id);
if (dto != null) {
List<ClassificationPath> cpl = dto.getClassPath(idSeg);
if (cpl.size() > 0) {
if (cpl.get(0).getScore()[level] == 0) {
return true;
}
} else {
return true;
}
}
return false;
}
});
semGui.getSegmentsTable().setRowSorter(sorter);
semGui.getStatusSegments().setText("Totale filtrati elementi: " + semGui.getSegmentsTable().getRowCount());
}
/**
* Gestisce l'evento per popolare la tabella files con il contenuto di una
* cartella
*
* @param sourceDir cartella sorgente
* @param filter file da caricare
* @param semGui frame
*/
public static void filesTableReadFolder(String sourceDir, File[] filter, SemGui semGui) {
if (semGui.getRtt() == null) {
Thread t = new Thread(() -> {
semGui.getInterrompi().setEnabled(true);
int processors = semGui.getProcessori2().getSelectedIndex() + 1;
GuiUtils.prepareTables(semGui);
semGui.setRtt(new ReadFolderToTable(processors));
if (semGui.getTableData() == null) {
semGui.setTableData(new ConcurrentHashMap<>());
}
semGui.updateLastSelectFolder(sourceDir);
semGui.getFilesTab().requestFocus();
semGui.getRtt().process(sourceDir, filter, semGui.getDP(), semGui.getFilesTable(), semGui.getFilesInfoLabel(), semGui.getTableData(), semGui.getPercorsoOCR().getText());
semGui.getFilesTab().setTitleAt(0, "Storage (" + semGui.getFilesTable().getRowCount() + ")");
semGui.getFilesTab().setTitleAt(1, "Segmenti (" + semGui.getSegmentsTable().getRowCount() + ")");
semGui.setRtt(null);
semGui.getInterrompi().setEnabled(false);
});
t.start();
}
}
/**
* Gestisce l'esportaizone excel della filestable (e dei segmenti)
*
* @param evt evento
* @param semGui frame
*/
public static void doExportToExcel(ActionEvent evt, SemGui semGui) {
semGui.getSelectExportExcel().setVisible(false);
String command = evt.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
File file = semGui.getExpotExcelFileChooser().getSelectedFile();
semGui.updateLastSelectFolder(file.getAbsolutePath());
String path = file.getAbsolutePath();
if (!path.endsWith(".xlsx")) {
path = path + ".xlsx";
}
semGui.getFilesInfoLabel().setText("Esportazione in corso...");
try {
FileOutputStream fos = new FileOutputStream(path);
SegmentationExcelWriter sew = new SegmentationExcelWriter(semGui.getSE());
int id = 1;
for (SemDocument dto : semGui.getTableData().values()) {
sew.addDocument(id++, dto.getFileName(), dto.getLanguage(), (String) dto.getRow()[8], String.valueOf(dto.getRow()[9]), dto.getIdentifiedSegments());
if (id % 7 == 0) {
semGui.getFilesInfoLabel().setText("Esportazione " + id + "/" + semGui.getTableData().size());
}
}
sew.write(fos);
fos.close();
} catch (Exception e) {
LogGui.printException(e);
}
semGui.getFilesInfoLabel().setText("Esportazione terminata");
}
});
t.start();
}
}
/**
* Gestisce l'importazione del .SER
*
* @param evt evento
* @param semGui frame
*/
public static void doImportSER(ActionEvent evt, SemGui semGui) {
semGui.getSelectOpenStorage().setVisible(false);
String command = evt.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
semGui.getFilesInfoLabel().setText("Apertura in corso...");
resetSegmentationsActionManagement(null, semGui);
GuiUtils.prepareTables(semGui);
FileInputStream finp;
try {
String path = semGui.getOpenFileChooser().getSelectedFile().getAbsolutePath();
semGui.updateLastSelectFolder(path);
finp = new FileInputStream(new File(path));
} catch (Exception e) {
LogGui.printException(e);
return;
}
try {
ObjectInputStream oos = new ObjectInputStream(finp);
semGui.setTableData((Map<Integer, SemDocument>) oos.readObject());
DefaultTableModel model = (DefaultTableModel) semGui.getFilesTable().getModel();
DefaultTableModel segModel = (DefaultTableModel) semGui.getSegmentsTable().getModel();
semGui.getTableData().keySet().stream().forEach((Integer id) -> {
SemDocument dto = semGui.getTableData().get(id);
Object[] r = dto.getRow();
if (r != null) {
Map<String, Integer> stats = dto.getStats();
if (stats != null) {
r[3] = stats.get("Segments");
r[4] = stats.get("ClassSegments");
r[5] = stats.get("Captures");
r[6] = stats.get("Sentencies");
r[7] = stats.get("Classifications");
}
model.addRow(r);
}
List<Object[]> rSegs = dto.getSegmentRows();
rSegs.stream().forEach((Object[] rSeg) -> {
segModel.addRow(rSeg);
});
if (id % 3 == 0) {
semGui.updateStats();
}
});
semGui.updateStats();
} catch (Exception e) {
LogGui.printException(e);
return;
}
try {
finp.close();
} catch (Exception e) {
LogGui.printException(e);
}
semGui.captureCoverageUpdate();
semGui.getFilesInfoLabel().setText("Dati caricati correttamente");
}
});
t.setDaemon(true);
t.start();
}
}
/**
* Aggiorna i KPI nella tabella dei files
*
* @param row riga
* @param column colonna
* @param kpi KPI
* @param semGui frame
*/
public static void updateFilesTable(int row, int column, Number kpi, SemGui semGui) {
row = semGui.getFilesTable().convertRowIndexToModel(row);
semGui.getFilesTable().getModel().setValueAt(kpi != null ? kpi : 0, row, column);
}
/**
* Esegue il tagcouding dei contenuti della files
*
* @param semGui frame
*/
public static void doFilesTableTagCloud(SemGui semGui) {
if (semGui.isIsClassify()) {
semGui.getStopTagCloud().setValue(true);
semGui.getInterrompi().setEnabled(false);
} else {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
if (!semGui.isIsClassify()) {
final TagCloudResults ret = getTagCloudResults(semGui, true);
semGui.openCloudFrame(ret, 200);
semGui.getFilesTab().setTitleAt(0, "Storage");
LogGui.info("Terminated...");
semGui.getFilesInfoLabel().setText("Fine");
semGui.setIsClassify(false);
semGui.getInterrompi().setEnabled(false);
}
}
});
t.setDaemon(true);
t.start();
}
}
/**
* Estrae le frequenze dei termini a partire da un tagcloud
*
* @since 1.3.3
* @param semGui frame
* @param fullText true se deve essere fatta sull'intero testo
*/
public static void doExtractFrequencies(SemGui semGui, boolean fullText) {
GuiUtils.clearTable(semGui.getFreqTable());
semGui.getFreqLabel().setText("Calcolo frequenze in corso...");
if (semGui.isIsClassify()) {
semGui.getStopTagCloud().setValue(true);
semGui.getInterrompi().setEnabled(false);
} else {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
if (!semGui.isIsClassify()) {
final TagCloudResults result = getTagCloudResults(semGui, fullText);
DefaultTableModel model = (DefaultTableModel) semGui.getFreqTable().getModel();
Cloud cloud = result.getCloud(10000); //10000 termini credo siano sufficienti
Map<Integer, SemDocument> map = semGui.getTableData();
semGui.getWordFrequencies().setVisible(true);
for (Tag tag : cloud.tags()) {
TagClass tc = result.getTagClass(tag);
Set<String> docIds = tc.getDocumentsId();
String language = "it";
try {
if (docIds.size() > 0) {
for (String id : docIds) {
Integer iid = Integer.parseInt(id);
SemDocument d = map.get(iid);
if (d != null) {
language = d.getLanguage();
break;
}
}
}
} catch (Exception e) {
}
String words = tc.getWordsString();
String[] wArray = words.split(" ");
for (String w : wArray) {
Object[] row = new Object[5];
row[0] = tag.getName();
row[1] = w;
row[2] = tag.getWeight();
row[3] = tag.getNormScore();
row[4] = language;
model.addRow(row);
}
}
semGui.getFilesTab().setTitleAt(0, "Storage");
semGui.getFreqLabel().setText("Frequenze calcolate. " + model.getRowCount() + " termini");
LogGui.info("Terminated...");
semGui.getFilesInfoLabel().setText("Fine");
semGui.setIsClassify(false);
semGui.getInterrompi().setEnabled(false);
}
}
});
t.setDaemon(true);
t.start();
}
}
private static TagCloudResults getTagCloudResults(SemGui semGui, boolean fullText) {
semGui.getStopTagCloud().setValue(false);
semGui.getInterrompi().setEnabled(true);
semGui.setIsClassify(true);
semGui.resetFilesFilters();
ChangedUtils.prepareChanged(semGui);
semGui.getFilesTab().setTitleAt(0, "Storage (" + semGui.getFilesTable().getRowCount() + ") - Tag cloud in corso");
int processors = semGui.getProcessori2().getSelectedIndex() + 1;
ParallelProcessor tagClouding = new ParallelProcessor(processors, 6000); //100 ore
AtomicInteger count = new AtomicInteger(0);
semGui.getME().resetAnalyzers(); //Resetta gli analyzers
LogGui.info("Start processing");
final int size = semGui.getFilesTable().getRowCount();
final TagCloudResults ret = new TagCloudResults();
for (int j = 0; j < processors; j++) {
tagClouding.add(() -> {
//Legge il file... e agginge in coda
while (true) {
if (semGui.getStopTagCloud().getValue()) {
break;
}
int row = count.getAndIncrement();
if (row >= size) {
break;
}
int pos = semGui.getFilesTable().convertRowIndexToModel(row);
Integer id = (Integer) semGui.getFilesTable().getValueAt(pos, 0);
SemDocument dto = semGui.getTableData().get(id);
String text = String.valueOf(dto.getRow()[8]);
if (!fullText) {
StringBuilder sb = new StringBuilder();
for (Object[] rowSeg : dto.getSegmentRows()) {
sb.append(rowSeg[4]).append("\n");
}
text = sb.toString();
}
if (text == null) {
text = "";
}
if (row % 3 == 0) {
semGui.getFilesTab().setTitleAt(0, "Storage (" + semGui.getFilesTable().getRowCount() + ") - " + row + "/" + size);
}
try {
String language = dto.getLanguage();
MyAnalyzer analyzer = semGui.getME().getAnalyzer(language);
Tokenizer.getTagClasses(ret, text, dto.getId(), analyzer);
} catch (Exception e) {
LogGui.printException(e);
}
} //Quello che legge
});
}
tagClouding.waitTermination();
return ret;
}
private static Object lockSync = new Object();
static void doAtomicSegment(String text, int id, int currentFilesPosition, boolean classify, SemGui semGui) {
try {
Map<SegmentConfiguration, List<SegmentationResults>> identifiedSegments;
SemDocument dto = semGui.getTableData().get(id);
SemDocument old = dto.clone();
String language = dto.getLanguage();
DefaultTableModel model = (DefaultTableModel) semGui.getSegmentsTable().getModel();
if (classify) {
identifiedSegments = semGui.getSE().getSegments(text, semGui.getME(), language);
} else {
identifiedSegments = semGui.getSE().getSegments(text, null, language);
}
dto.setIdentifiedSegments(identifiedSegments);
Map<String, Integer> stats = dto.getStats();
FilesAndSegmentsUtils.updateFilesTable(currentFilesPosition, 3, stats.get("Segments"), semGui);
FilesAndSegmentsUtils.updateFilesTable(currentFilesPosition, 4, stats.get("ClassSegments"), semGui);
FilesAndSegmentsUtils.updateFilesTable(currentFilesPosition, 5, stats.get("Captures"), semGui);
FilesAndSegmentsUtils.updateFilesTable(currentFilesPosition, 6, stats.get("Sentencies"), semGui);
FilesAndSegmentsUtils.updateFilesTable(currentFilesPosition, 7, stats.get("Classifications"), semGui);
if (!semGui.getEvaluations().isEmpty()) {
double rank = semGui.getEvaluations().evaluate(identifiedSegments);
//dto.getRow()[10] = rank;
FilesAndSegmentsUtils.updateFilesTable(currentFilesPosition, 10, rank, semGui);
}
ChangedUtils.updateChangedTable(dto, old, semGui);
List<Object[]> rows = dto.getSegmentRows();
synchronized (lockSync) {
rows.stream().forEach((Object[] row) -> {
model.addRow(row);
});
}
} catch (Exception e) {
LogGui.printException(e);
}
}
/**
* Gestisce la segmentazione della tabella files
*
* @param classify true se deve anche classificare
* @param semGui frame
*/
public static void doFilesTableSegment(boolean classify, SemGui semGui) {
if (semGui.isIsClassify()) {
semGui.getStopSegmentAndClassify().setValue(true);
semGui.getInterrompi().setEnabled(false);
} else {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
if (!semGui.isIsClassify()) {
semGui.getStopSegmentAndClassify().setValue(false);
semGui.getInterrompi().setEnabled(true);
semGui.setIsClassify(true);
semGui.resetFilesFilters();
ChangedUtils.prepareChanged(semGui);
GuiUtils.clearTable(semGui.getSegmentsTable());
semGui.getFilesTab().setTitleAt(0, "Storage (" + semGui.getFilesTable().getRowCount() + ") - Inizializzazione");
semGui.getFilesTab().setTitleAt(1, "Segmenti (" + semGui.getSegmentsTable().getRowCount() + ")");
semGui.getFilesTab().setTitleAt(2, "Cambiamenti (" + semGui.getChangedTable().getRowCount() + ")");
if (semGui.isNeedUpdate()) {
semGui.getRebuildIndex().setSelected(true);
semGui.initializeModel();
semGui.setNeedUpdate(false);
}
semGui.getFilesTab().setTitleAt(0, "Storage (" + semGui.getFilesTable().getRowCount() + ") - Classificazione in corso");
int processors = semGui.getProcessori2().getSelectedIndex() + 1;
ParallelProcessor segmentAndClassify = new ParallelProcessor(processors, 6000); //100 ore
AtomicInteger count = new AtomicInteger(0);
LogGui.info("Start processing");
final int size = semGui.getFilesTable().getRowCount();
for (int j = 0; j < processors; j++) {
segmentAndClassify.add(() -> {
//Legge il file... e agginge in coda
while (true) {
if (semGui.getStopSegmentAndClassify().getValue()) {
break;
}
int row = count.getAndIncrement();
if (row >= size) {
break;
}
int pos = semGui.getFilesTable().convertRowIndexToModel(row);
Integer id = (Integer) semGui.getFilesTable().getValueAt(pos, 0);
SemDocument dto = semGui.getTableData().get(id);
String text = String.valueOf(dto.getRow()[8]);
if (text == null) {
text = "";
}
if (row % 3 == 0) {
semGui.getFilesTab().setTitleAt(0, "Storage (" + semGui.getFilesTable().getRowCount() + ") - " + row + "/" + size);
semGui.getFilesTab().setTitleAt(1, "Segmenti (" + semGui.getSegmentsTable().getRowCount() + ")");
semGui.getFilesTab().setTitleAt(2, "Cambiamenti (" + semGui.getChangedTable().getRowCount() + ")");
}
FilesAndSegmentsUtils.doAtomicSegment(text, id, pos, true, semGui);
} //Quello che legge
});
}
segmentAndClassify.waitTermination();
ChangedUtils.updateChangedTree(semGui);
LogGui.info("Terminated...");
GuiUtils.runGarbageCollection();
semGui.getFilesInfoLabel().setText("Fine");
semGui.updateStats();
semGui.setIsClassify(false);
semGui.captureCoverageUpdate();
semGui.getInterrompi().setEnabled(false);
GuiUtils.filterOnStatus("C", null, semGui);
}
}
});
t.setDaemon(true);
t.start();
}
}
/**
* Gestisce il popolamento della filesTable attraverso excel
*
* @param evt evento
* @param semGui frame
*/
public static void doFilesTableImportExcel(ActionEvent evt, SemGui semGui) {
semGui.getSelectExcelFileSer().setVisible(false);
String command = evt.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)) {
GuiUtils.prepareTables(semGui);
final String fileName = semGui.getExcelCorpusChooser().getSelectedFile().getAbsolutePath();
semGui.updateLastSelectFolder(fileName);
Thread t = new Thread(() -> {
ReadExcelToTable rtt = new ReadExcelToTable();
if (semGui.getTableData() == null) {
semGui.setTableData(new ConcurrentHashMap<>());
}
rtt.process(fileName, semGui.getDP(), semGui.getFilesTable(), semGui.getFilesInfoLabel(), semGui.getTableData());
});
t.setDaemon(true);
t.start();
}
}
/**
* Gestisce il reset (ripristino) dell'interfaccia
*
* @param evt evento
* @param semGui frame
* @throws HeadlessException eccezione
*/
public static void resetSegmentationsActionManagement(ActionEvent evt, SemGui semGui) throws HeadlessException {
if (semGui.isIsClassify()) {
return;
}
int dialogResult;
if (evt == null) {
dialogResult = JOptionPane.YES_OPTION;
} else {
int dialogButton = JOptionPane.YES_NO_OPTION;
dialogResult = JOptionPane.showConfirmDialog(null, "Confermi la pulizia completa del lavoro?", "Warning", dialogButton);
}
if (dialogResult == JOptionPane.YES_OPTION) {
GuiUtils.clearTable(semGui.getFilesTable());
GuiUtils.clearTable(semGui.getSegmentsTable());
GuiUtils.clearTable(semGui.getFilesPanleCapturesTable());
GuiUtils.clearTable(semGui.getChangedTable());
GuiUtils.clearTable(semGui.getCoverageTable());
GuiUtils.clearTable(semGui.getCaptureValues());
GuiUtils.clearTable(semGui.getCoverageDocumentsTable());
DefaultMutableTreeNode treeNode1 = new DefaultMutableTreeNode("Nessun elemento");
semGui.getSegmentClassificationResult().setModel(new DefaultTreeModel(treeNode1));
semGui.getFilesPanelSegmentTree().setModel(new DefaultTreeModel(treeNode1));
semGui.getChangedFilterTree().setModel(new DefaultTreeModel(treeNode1));
semGui.getFileText().setText("");
semGui.getFilesPanelHtmlFormatted().setText("");
semGui.getFilesPanelHtml().setContentType("text/html");
semGui.getFilesPanelHtml().setText("");
semGui.getSegmentText().setText("");
semGui.getImagesPanel().removeAll();
semGui.getSegmentTokens().setText("");
if (semGui.getTableData() != null) {
semGui.getTableData().clear();
}
semGui.updateStats();
}
return;
}
/**
* Rimuove i duplicati nella tabella dei files basandosi sul testo
* tokenizzato
*
* @since 1.2
*
* @param semGui frame
*/
public static void removeDuplicates(SemGui semGui) {
if (semGui.isIsClassify()) {
semGui.getStopTagCloud().setValue(true);
semGui.getInterrompi().setEnabled(false);
} else {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
if (!semGui.isIsClassify()) {
semGui.getStopTagCloud().setValue(false);
semGui.getInterrompi().setEnabled(true);
semGui.setIsClassify(true);
semGui.resetFilesFilters();
ChangedUtils.prepareChanged(semGui);
JTable filesTable = semGui.getFilesTable();
JTable segTable = semGui.getSegmentsTable();
DefaultTableModel model = (DefaultTableModel) filesTable.getModel();
DefaultTableModel segModel = (DefaultTableModel) segTable.getModel();
int count = model.getRowCount();
Set<String> texts = new HashSet<>();
Set<String> segToDelete = new HashSet<>();
Set<String> fileToDelete = new HashSet<>();
for (int i = count - 1; i >= 0; i--) {
int pos = filesTable.convertRowIndexToModel(i);
Integer id = (Integer) filesTable.getValueAt(pos, 0);
SemDocument dto = semGui.getTableData().get(id);
if (dto == null) {
continue;
}
String text = String.valueOf(dto.getRow()[8]);
if (text == null) {
text = "";
}
text = semGui.getME().tokenize(text, String.valueOf(dto.getRow()[2]), -1);
if (!texts.contains(text)) {
texts.add(text);
} else {
List<Object[]> sr = dto.getSegmentRows();
for (Object[] s : sr) {
segToDelete.add((String) s[0]);
}
semGui.getTableData().remove(id);
model.removeRow(pos);
}
}
int rc = segModel.getRowCount();
for (int i = rc - 1; i >= 0; i--) {
if (segToDelete.contains(segModel.getValueAt(i, 0))) {
segModel.removeRow(i);
}
}
semGui.updateStats();
LogGui.info("Terminated...");
semGui.getFilesInfoLabel().setText("Fine");
semGui.setIsClassify(false);
semGui.getInterrompi().setEnabled(false);
}
}
});
t.setDaemon(true);
t.start();
}
}
/**
*
* @param semGui
*/
public static void doSegmentTableClass(SemGui semGui) {
if (semGui.isIsClassify()) {
semGui.getStopSegmentAndClassify().setValue(true);
semGui.getInterrompi().setEnabled(false);
} else {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
if (!semGui.isIsClassify()) {
semGui.getStopSegmentAndClassify().setValue(false);
semGui.getInterrompi().setEnabled(true);
semGui.setIsClassify(true);
semGui.resetFilesFilters();
ChangedUtils.prepareChanged(semGui);
semGui.getFilesTab().setTitleAt(0, "Storage (" + semGui.getFilesTable().getRowCount() + ")");
semGui.getFilesTab().setTitleAt(1, "Segmenti (" + semGui.getSegmentsTable().getRowCount() + ")");
semGui.getFilesTab().setTitleAt(2, "Cambiamenti (" + semGui.getChangedTable().getRowCount() + ")");
if (semGui.isNeedUpdate()) {
semGui.getRebuildIndex().setSelected(true);
//semGui.getRebuildIndex().setSelected(false);
semGui.initializeModel(false);
semGui.setNeedUpdate(false);
}
semGui.getFilesTab().setTitleAt(1, "Segmenti (" + semGui.getSegmentsTable().getRowCount() + ") - Classificazione in corso");
int processors = semGui.getProcessori2().getSelectedIndex() + 1;
ParallelProcessor segmentAndClassify = new ParallelProcessor(processors, 6000); //100 ore
AtomicInteger count = new AtomicInteger(0);
LogGui.info("Start processing");
final int size = semGui.getSegmentsTable().getRowCount();
for (int j = 0; j < processors; j++) {
segmentAndClassify.add(() -> {
//Legge il file... e agginge in coda
while (true) {
if (semGui.getStopSegmentAndClassify().getValue()) {
break;
}
int row = count.getAndIncrement();
if (row >= size) {
break;
}
int pos = semGui.getSegmentsTable().convertRowIndexToModel(row);
String idSeg = String.valueOf(semGui.getSegmentsTable().getValueAt(pos, 0));
int p2 = idSeg.indexOf(".");
Integer id = Integer.parseInt(idSeg.substring(0, p2));
SemDocument dto = semGui.getTableData().get(id);
List<Object[]> rows = dto.getSegmentRows();
int posSegRow = -1;
for (int k = 0; k < rows.size(); k++) {
Object[] rx = rows.get(k);
if (String.valueOf(rx[0]).equals(idSeg)) {
posSegRow = k;
break;
}
}
String text = String.valueOf(semGui.getSegmentsTable().getValueAt(pos, 4));
String lang = String.valueOf(semGui.getSegmentsTable().getValueAt(pos, 3));
if (text == null) {
text = "";
continue;
}
if (row % 3 == 0) {
semGui.getFilesTab().setTitleAt(1, "Segmenti (" + semGui.getSegmentsTable().getRowCount() + ") - " + row + "/" + size);
}
String language = dto.getLanguage();
List<ClassificationPath> bayes = semGui.getME().bayesClassify(text, language);
String oldClass1 = String.valueOf(semGui.getSegmentsTable().getValueAt(pos, 1));
String oldClass2 = String.valueOf(semGui.getSegmentsTable().getValueAt(pos, 2));
String newClass1 = "";
String newClass2 = "";
if (bayes.size() == 1) {
newClass1 = bayes.get(0).toSmallClassString();
} else if (bayes.size() >= 2) {
newClass1 = bayes.get(0).toSmallClassString();
newClass2 = bayes.get(1).toSmallClassString();
}
String check = String.valueOf(semGui.getSegmentsTable().getValueAt(pos, 6));
if (!"I".equalsIgnoreCase(check)) {
if ("X".equalsIgnoreCase(check)) {
if (!newClass1.equalsIgnoreCase(oldClass1)
&& !newClass1.equalsIgnoreCase(oldClass2)
&& !newClass2.equalsIgnoreCase(oldClass1)
&& !newClass2.equalsIgnoreCase(oldClass2)) {
semGui.getSegmentsTable().setValueAt("A", pos, 6);
rows.get(posSegRow)[6] = "A";
}
} else if (!newClass1.equalsIgnoreCase(oldClass1) || !newClass2.equalsIgnoreCase(oldClass2)) {
semGui.getSegmentsTable().setValueAt("C", pos, 6);
rows.get(posSegRow)[6] = "C";
} else {
semGui.getSegmentsTable().setValueAt("", pos, 6);
rows.get(posSegRow)[6] = "";
}
}
semGui.getSegmentsTable().setValueAt(newClass1, pos, 1);
semGui.getSegmentsTable().setValueAt(newClass2, pos, 2);
rows.get(posSegRow)[1] = newClass1;
rows.get(posSegRow)[2] = newClass2;
dto.setClassPath(idSeg, bayes);
dto.setSegmentRows(rows);
} //Quello che legge
});
}
segmentAndClassify.waitTermination();
ChangedUtils.updateChangedTree(semGui);
LogGui.info("Terminated...");
GuiUtils.runGarbageCollection();
semGui.getFilesInfoLabel().setText("Fine");
semGui.updateStats();
semGui.setIsClassify(false);
semGui.captureCoverageUpdate();
semGui.getInterrompi().setEnabled(false);
GuiUtils.filterOnStatus("C", null, semGui);
}
}
});
t.setDaemon(true);
t.start();
}
}
}
| 49.151485 | 185 | 0.502266 |
cc7cbdb0ccad780070eee1b429877ffbcf1241bf | 241 | package stexfires.io;
import stexfires.io.spec.RecordFileSpec;
import java.nio.file.Path;
/**
* @author Mathias Kalb
* @since 0.1
*/
public interface RecordFile<S extends RecordFileSpec> {
Path getPath();
S getFileSpec();
}
| 13.388889 | 55 | 0.697095 |
8a4205323198c1e7fa2d899fccc23a805651382e | 2,069 | /**
* Copyright © Microsoft Open Technologies, Inc.
*
* 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
*
* THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
* ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
* PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache License, Version 2.0 for the specific language
* governing permissions and limitations under the License.
*/
package com.msopentech.odatajclient.engine.data.metadata.edm;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.msopentech.odatajclient.engine.data.metadata.edm.AbstractEdm;
import com.msopentech.odatajclient.engine.data.metadata.edm.DataServicesDeserializer;
import com.msopentech.odatajclient.engine.data.metadata.edm.Schema;
import java.util.ArrayList;
import java.util.List;
@JsonDeserialize(using = DataServicesDeserializer.class)
public class DataServices extends AbstractEdm {
private static final long serialVersionUID = -9126377222393876166L;
private String dataServiceVersion;
private String maxDataServiceVersion;
private List<Schema> schemas = new ArrayList<Schema>();
public String getDataServiceVersion() {
return dataServiceVersion;
}
public void setDataServiceVersion(final String dataServiceVersion) {
this.dataServiceVersion = dataServiceVersion;
}
public String getMaxDataServiceVersion() {
return maxDataServiceVersion;
}
public void setMaxDataServiceVersion(final String maxDataServiceVersion) {
this.maxDataServiceVersion = maxDataServiceVersion;
}
public List<Schema> getSchemas() {
return schemas;
}
public void setSchemas(final List<Schema> schemas) {
this.schemas = schemas;
}
}
| 32.328125 | 85 | 0.755921 |
3d31ec9ae29b64798254c6cc3e36bf15c8aaa028 | 1,425 | /*
* 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.uima.ruta.ide.parser.ast;
import org.eclipse.dltk.ast.Modifiers;
import org.eclipse.dltk.ast.references.SimpleReference;
public class RutaImportStatement extends RutaSimpleStatement {
private int type;
public RutaImportStatement(int sourceStart, int sourceEnd, SimpleReference importRef, int type) {
super(sourceStart, sourceEnd, importRef);
this.type = type;
}
@Override
public int getKind() {
return Modifiers.AccNameSpace;
}
/**
* See {@link RutaStatementConstants}
*
* @return type of import
*/
public int getType() {
return this.type;
}
}
| 29.6875 | 99 | 0.73614 |
9f97bcd54bf8faeba74c41af11f51b833e3d9817 | 507 | package sh.evc.sdk.wechat.mp.domain.customer;
/**
* 客服消息文本
*
* @author winixi
* @date 2019-06-07 16:36
*/
public class Text {
/**
* 消息内容
*/
private String content;
public Text(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Text{" +
"content='" + content + '\'' +
'}';
}
}
| 14.485714 | 45 | 0.57002 |
fce946a605120c6efc149455e30a42b502daa143 | 8,094 | /*
* MIT License
*
* Copyright (c) 2017 SnowShock35
*
* 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.snowshock35.jeiintegration.config;
import com.snowshock35.jeiintegration.JEIIntegration;
import net.minecraft.client.resources.I18n;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.io.File;
public class Config {
static final String CATEGORY_HANDLERS = "Handler Settings";
static final String CATEGORY_TOOLTIPS = "Tooltip Settings";
static final String CATEGORY_MISCELLANEOUS = "Miscellaneous Settings";
private static final String defaultBurnTimeTooltipMode = "disabled";
private static final String defaultDurabilityTooltipMode = "disabled";
private static final String defaultFluidRegInfoTooltipMode = "disabled";
private static final String defaultRegistryNameTooltipMode = "disabled";
private static final String defaultMaxStackSizeTooltipMode = "disabled";
private static final String defaultMetadataTooltipMode = "disabled";
private static final String defaultNbtTooltipMode = "disabled";
private static final String defaultOreDictEntriesTooltipMode = "disabled";
private static final String defaultUnlocalizedNameTooltipMode = "disabled";
private final Configuration config;
private String burnTimeTooltipMode = "";
private String durabilityTooltipMode = "";
private String fluidRegInfoTooltipMode = "";
private String registryNameTooltipMode = "";
private String maxStackSizeTooltipMode = "";
private String metadataTooltipMode = "";
private String nbtTooltipMode = "";
private String oreDictEntriesTooltipMode = "";
private String unlocalizedNameTooltipMode = "";
public Config(FMLPreInitializationEvent e) {
final File configFile = new File(e.getModConfigurationDirectory(), JEIIntegration.MOD_ID + ".cfg");
config = new Configuration(configFile, "1.0.0");
loadConfig();
}
private void loadConfig() {
config.setCategoryLanguageKey(CATEGORY_HANDLERS, "config.jeiintegration.handlers");
config.setCategoryLanguageKey(CATEGORY_TOOLTIPS, "config.jeiintegration.tooltips");
config.setCategoryLanguageKey(CATEGORY_MISCELLANEOUS, "config.jeiintegration.miscellaneous");
config.addCustomCategoryComment(CATEGORY_HANDLERS, I18n.format("config.jeiintegration.handlers.comment"));
config.addCustomCategoryComment(CATEGORY_TOOLTIPS, I18n.format("config.jeiintegration.tooltips.comment"));
config.addCustomCategoryComment(CATEGORY_MISCELLANEOUS, I18n.format("config.jeiintegration.miscellaneous.comment"));
burnTimeTooltipMode = config.getString("burnTimeTooltipMode", CATEGORY_TOOLTIPS, defaultBurnTimeTooltipMode, I18n.format("config.jeiintegration.tooltips.burnTimeTooltipMode.comment"), new String[] {"disabled", "enabled", "onShift", "onDebug", "onShiftAndDebug"}, "config.jeiintegration.tooltips.burnTimeTooltipMode");
durabilityTooltipMode = config.getString("durabilityTooltipMode", CATEGORY_TOOLTIPS, defaultDurabilityTooltipMode, I18n.format("config.jeiintegration.tooltips.durabilityTooltipMode.comment"), new String[] {"disabled", "enabled", "onShift", "onDebug", "onShiftAndDebug"}, "config.jeiintegration.tooltips.durabilityTooltipMode");
fluidRegInfoTooltipMode = config.getString("fluidRegInfoTooltipMode", CATEGORY_TOOLTIPS, defaultFluidRegInfoTooltipMode, I18n.format("config.jeiintegration.tooltips.fluidRegInfoTooltipMode.comment"), new String[] {"disabled", "enabled", "onShift", "onDebug", "onShiftAndDebug"}, "config.jeiintegration.tooltips.fluidRegInfoTooltipMode");
registryNameTooltipMode = config.getString("registryNameTooltipMode", CATEGORY_TOOLTIPS, defaultRegistryNameTooltipMode, I18n.format("config.jeiintegration.tooltips.registryNameTooltipMode.comment"), new String[] {"disabled", "enabled", "onShift", "onDebug", "onShiftAndDebug"}, "config.jeiintegration.tooltips.registryNameTooltipMode");
maxStackSizeTooltipMode = config.getString("maxStackSizeTooltipMode", CATEGORY_TOOLTIPS, defaultMaxStackSizeTooltipMode, I18n.format("config.jeiintegration.tooltips.maxStackSizeTooltipMode.comment"), new String[] {"disabled", "enabled", "onShift", "onDebug", "onShiftAndDebug"}, "config.jeiintegration.tooltips.maxStackSizeTooltipMode");
metadataTooltipMode = config.getString("metadataTooltipMode", CATEGORY_TOOLTIPS, defaultMetadataTooltipMode, I18n.format("config.jeiintegration.tooltips.metadataTooltipMode.comment"), new String[] {"disabled", "enabled", "onShift", "onDebug", "onShiftAndDebug"}, "config.jeiintegration.tooltips.metadataTooltipMode");
nbtTooltipMode = config.getString("nbtTooltipMode", CATEGORY_TOOLTIPS, defaultNbtTooltipMode, I18n.format("config.jeiintegration.tooltips.nbtTooltipMode.comment"), new String[] {"disabled", "enabled", "onShift", "onDebug", "onShiftAndDebug"}, "config.jeiintegration.tooltips.nbtTooltipMode");
oreDictEntriesTooltipMode = config.getString("oreDictEntriesTooltipMode", CATEGORY_TOOLTIPS, defaultOreDictEntriesTooltipMode, I18n.format("config.jeiintegration.tooltips.oreDictEntriesTooltipMode.comment"), new String[] {"disabled", "enabled", "onShift", "onDebug", "onShiftAndDebug"}, "config.jeiintegration.tooltips.oreDictEntriesTooltipMode");
unlocalizedNameTooltipMode = config.getString("unlocalizedNameTooltipMode", CATEGORY_TOOLTIPS, defaultUnlocalizedNameTooltipMode, I18n.format("config.jeiintegration.tooltips.unlocalizedNameTooltipMode.comment"), new String[] {"disabled", "enabled", "onShift", "onDebug", "onShiftAndDebug"}, "config.jeiintegration.tooltips.unlocalizedNameTooltipMode");
if (config.hasChanged()) {
config.save();
}
}
public Configuration getConfig() {
return config;
}
public String getBurnTimeTooltipMode() {
return burnTimeTooltipMode;
}
public String getDurabilityTooltipMode() {
return durabilityTooltipMode;
}
public String getFluidRegInfoTooltipMode() {
return fluidRegInfoTooltipMode;
}
public String getRegistryNameTooltipMode() {
return registryNameTooltipMode;
}
public String getMaxStackSizeTooltipMode() {
return maxStackSizeTooltipMode;
}
public String getMetadataTooltipMode() {
return metadataTooltipMode;
}
public String getNbtTooltipMode() {
return nbtTooltipMode;
}
public String getOreDictEntriesTooltipMode() {
return oreDictEntriesTooltipMode;
}
public String getUnlocalizedNameTooltipMode() {
return unlocalizedNameTooltipMode;
}
@SubscribeEvent
public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent eventArgs) {
if (JEIIntegration.MOD_ID.equals(eventArgs.getModID())) {
loadConfig();
}
}
}
| 58.230216 | 360 | 0.7681 |
a40a0b113270dc909e3485de29f4c85aa319b79f | 477 | package com.saurav.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.saurav.base.TestBase;
public class AddressPage extends TestBase{
@FindBy(xpath="(//button[@type='submit'])[2]")
WebElement checkout;
public AddressPage() {
PageFactory.initElements(driver, this);
}
public ShippingPage clickOnCheckout() {
checkout.submit();
return new ShippingPage();
}
}
| 19.875 | 47 | 0.752621 |
5195ac680ef63282a8d95ede1b2179dbe4353e49 | 3,504 | package org.vaadin.activiti.simpletravel.domain;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.vaadin.activiti.simpletravel.domain.validation.ReturnsAfterDeparture;
import com.github.peholmst.stuff4vaadin.clone.CloneThis;
@Entity
@ReturnsAfterDeparture(message = "The return date cannot be before the departure date")
public class TravelRequest extends AbstractEntity {
public static final String PROP_DEPARTURE_DATE = "departureDate";
public static final String PROP_RETURN_DATE = "returnDate";
public static final String PROP_COUNTRY = "country";
public static final String PROP_DESCRIPTION = "description";
@Column(nullable = false)
protected String requesterUserId;
@Column(nullable = false)
protected String requesterUserName;
@Temporal(TemporalType.DATE)
@Column(nullable = false)
@NotNull(message = "Please provide a departure date")
protected Date departureDate;
@Temporal(TemporalType.DATE)
@Column(nullable = false)
@NotNull(message = "Please provide a return date")
protected Date returnDate;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
@NotNull(message = "Please select the country you are traveling to")
protected Country country;
@Column(nullable = false)
@NotNull(message = "Please enter a description of your trip")
@Size(min = 3, message = "Please enter a description of your trip")
protected String description;
@OneToOne(orphanRemoval = true, cascade = CascadeType.ALL)
@CloneThis
@Valid
protected TravelRequestDecision decision;
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public Date getDepartureDate() {
return departureDate;
}
public void setDepartureDate(Date departureDate) {
this.departureDate = departureDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRequesterUserId() {
return requesterUserId;
}
public void setRequesterUserId(String requesterUserId) {
this.requesterUserId = requesterUserId;
}
public String getRequesterFullName() {
return requesterUserName;
}
public void setRequesterUserName(String requesterUserName) {
this.requesterUserName = requesterUserName;
}
public Date getReturnDate() {
return returnDate;
}
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}
/**
* Returns a clone of the travel request decision.
*/
public TravelRequestDecision getDecision() {
return decision != null ? (TravelRequestDecision) decision.clone() : null;
}
public void setDecision(TravelRequestDecision decision) {
this.decision = decision != null ? (TravelRequestDecision) decision.clone() : null;
}
public boolean isDecisionPending() {
return this.decision == null;
}
}
| 29.948718 | 91 | 0.716039 |
2561a63ffb1c0642ce284cd53de768bc444613cb | 929 | package com.communote.server.web.commons.resource;
import javax.servlet.http.HttpServletRequest;
import com.communote.common.util.Orderable;
/**
* Provider which defines the URL from which a favicon icon can be downloaded.
*
* @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a>
*/
public interface FaviconProvider extends Orderable {
/**
* Return the absolute or relative URL to the favicon icon exposed by this provider. The URL
* should contain a timestamp parameter or something comparable which reflects the time of the
* last modification of the icon to ensure that the URL changes when the icon is modified and
* thus, avoid unwanted browser caching effects.
*
* @param request
* the current request
* @return the URL to the favicon icon
*/
String getUrl(HttpServletRequest request);
}
| 35.730769 | 99 | 0.697524 |
c6ad42c43f6eb0dfaad6b43ca4f6d9e8d18cd95f | 10,144 | package net.mizucoffee.onenightwerewolf.welcome;
import android.app.ProgressDialog;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ObservableInt;
import android.databinding.adapters.SeekBarBindingAdapter;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.ValueEventListener;
import net.mizucoffee.onenightwerewolf.Jinro;
import net.mizucoffee.onenightwerewolf.R;
import net.mizucoffee.onenightwerewolf.Room;
import net.mizucoffee.onenightwerewolf.databinding.FragmentSetPositionBinding;
import java.lang.reflect.Field;
import java.util.ArrayList;
public class SetPositionFragment extends Fragment {
public final ObservableInt werewolf = new ObservableInt();
public final ObservableInt seer = new ObservableInt();
public final ObservableInt robber = new ObservableInt();
public final ObservableInt minion = new ObservableInt();
public final ObservableInt tanner = new ObservableInt();
public final ObservableInt playerNum = new ObservableInt();
FragmentSetPositionBinding mBinding;
FirebaseDatabase mDatabase;
WelcomeActivity activity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (WelcomeActivity) getActivity();
}
@Override
public void onDetach() {
super.onDetach();
activity = null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_set_position, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.bind(getView());
mBinding.setPosition(this);
activity.setSupportActionBar(mBinding.toolbar);
mDatabase = FirebaseDatabase.getInstance();
Typeface mplusLight = Typeface.createFromAsset(getContext().getAssets(), "mplus-1c-light.ttf");
TextView titleTextView = null;
try {
Field f = mBinding.toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView) f.get(mBinding.toolbar);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (titleTextView != null) titleTextView.setTypeface(mplusLight);
activity.setTitle( activity.getTitle() + " ID:" + activity.room.getRoomId() );
playerNum.set(activity.room.getPlayerNum());
switch (activity.room.getPlayerNum()) {
case 3:
werewolf.set(0);
seer.set(1);
robber.set(0);
minion.set(1);
tanner.set(0);
break;
case 4:
werewolf.set(1);
seer.set(1);
robber.set(1);
minion.set(1);
tanner.set(0);
break;
case 5:
werewolf.set(1);
seer.set(1);
robber.set(1);
minion.set(1);
tanner.set(1);
break;
case 6:
werewolf.set(1);
seer.set(2);
robber.set(1);
minion.set(1);
tanner.set(1);
break;
}
activity.room.setWerewolf(werewolf.get() + 1);
activity.room.setSeerc(seer.get());
activity.room.setRobber(robber.get());
activity.room.setMinion(minion.get());
activity.room.setTanner(tanner.get());
activity.room.setVillager(playerNum.get() -
(werewolf.get() +
seer.get() +
robber.get() +
minion.get() +
tanner.get() + 1) + 2);
activity.send();
}
public SeekBarBindingAdapter.OnProgressChanged progressChanged = new SeekBarBindingAdapter.OnProgressChanged() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int v = playerNum.get() -
(mBinding.werewolfSb.getProgress() +
mBinding.seerSb.getProgress() +
mBinding.robberSb.getProgress() +
mBinding.minionSb.getProgress() +
mBinding.tannerSb.getProgress() - 1);
if (v < 0)
seekBar.setProgress(seekBar.getProgress() + v);
activity.room.setWerewolf(mBinding.werewolfSb.getProgress() + 1);
activity.room.setSeerc(mBinding.seerSb.getProgress());
activity.room.setRobber(mBinding.robberSb.getProgress());
activity.room.setMinion(mBinding.minionSb.getProgress());
activity.room.setTanner(mBinding.tannerSb.getProgress());
activity.room.setVillager(playerNum.get() -
(mBinding.werewolfSb.getProgress() +
mBinding.seerSb.getProgress() +
mBinding.robberSb.getProgress() +
mBinding.minionSb.getProgress() +
mBinding.tannerSb.getProgress() + 1) + 2);
activity.send();
}
};
public void next(View v){
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setTitle("読込中");
progressDialog.setMessage("しばらくお待ち下さい...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
ArrayList<Integer> cards = new ArrayList<>();
for(int i = 0;i <= 5; i++){
switch (i){
case 0:
for (int j = 0;j < (werewolf.get() + 1);j++)
cards.add(Jinro.WEREWOLF);
break;
case 1:
for (int j = 0;j < seer.get();j++)
cards.add(Jinro.SEER);
break;
case 2:
for (int j = 0;j < robber.get();j++)
cards.add(Jinro.ROBBER);
break;
case 3:
for (int j = 0;j < minion.get();j++)
cards.add(Jinro.MINION);
break;
case 4:
for (int j = 0;j < tanner.get();j++)
cards.add(Jinro.TANNER);
break;
case 5:
for (int j = 0;j < (playerNum.get() -
(mBinding.werewolfSb.getProgress() +
mBinding.seerSb.getProgress() +
mBinding.robberSb.getProgress() +
mBinding.minionSb.getProgress() +
mBinding.tannerSb.getProgress() + 1) + 2 );j++)
cards.add(Jinro.VILLAGER);
break;
}
}
activity.room.setWerewolf(mBinding.werewolfSb.getProgress() + 1);
activity.room.setSeerc(mBinding.seerSb.getProgress());
activity.room.setRobber(mBinding.robberSb.getProgress());
activity.room.setMinion(mBinding.minionSb.getProgress());
activity.room.setTanner(mBinding.tannerSb.getProgress());
activity.room.setVillager(playerNum.get() -
(mBinding.werewolfSb.getProgress() +
mBinding.seerSb.getProgress() +
mBinding.robberSb.getProgress() +
mBinding.minionSb.getProgress() +
mBinding.tannerSb.getProgress() + 1) + 2);
activity.room.setCards(cards);
activity.room.setPhase(1);
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("room");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<ArrayList<Room>> genericTypeIndicator = new GenericTypeIndicator<ArrayList<Room>>() {};
ArrayList<Room> list = dataSnapshot.getValue(genericTypeIndicator);
if(list == null) list = new ArrayList<>();
for(int i = 0;i != list.size();i++)
if(list.get(i).getRoomId().equals(activity.room.getRoomId()))
list.set(i,activity.room);
ref.setValue(list);
progressDialog.hide();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment,new SetUsernameFragment());
transaction.addToBackStack(null);
transaction.commit();
}
@Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException().printStackTrace();
System.out.println("error"+databaseError.getDetails());
progressDialog.hide();
Toast.makeText(getContext(),"エラーが発生しました。",Toast.LENGTH_SHORT).show();
}
});
}
} | 39.780392 | 124 | 0.5764 |
0bcd6d216e36fa302068cb8f642bf444402f64f6 | 2,276 | package sensor;
import core.Sensor;
import edu.wpi.first.wpilibj.ADXL345_I2C;
import event.events.ADXL345Event;
import event.listeners.ADXL345Listener;
import java.util.Enumeration;
import java.util.Vector;
/**
* Wrapper for the ADXL345 accelerometer. Measures X, Y, and Z accelerations in
* G's (doesn't account for gravity)
*
* @author gerberduffy
*/
public class GRTADXL345 extends Sensor {
private ADXL345_I2C accelerometer;
private static final int X_AXIS = 0;
private static final int Y_AXIS = 1;
private static final int Z_AXIS = 2;
private static final int NUM_DATA = 3;
private Vector listeners;
/**
* Instantiates a new ADXL345.
*
* @param moduleNum number of digital module the accelerometer is connected
* to
* @param name name of sensor
*/
public GRTADXL345(int moduleNum, String name) {
super(name, NUM_DATA);
accelerometer = new ADXL345_I2C(moduleNum,
ADXL345_I2C.DataFormat_Range.k2G);
listeners = new Vector();
}
protected void poll() {
setState(X_AXIS, accelerometer.getAcceleration(ADXL345_I2C.Axes.kX));
setState(Y_AXIS, accelerometer.getAcceleration(ADXL345_I2C.Axes.kY));
setState(Z_AXIS, accelerometer.getAcceleration(ADXL345_I2C.Axes.kZ));
}
public void addADXL345Listener(ADXL345Listener l) {
listeners.addElement(l);
}
public void removeADXL345Listener(ADXL345Listener l) {
listeners.removeElement(l);
}
protected void notifyListeners(int id, double newDatum) {
ADXL345Event e = new ADXL345Event(this, id, newDatum);
switch (id) {
case X_AXIS: {
for (Enumeration en = listeners.elements(); en.hasMoreElements();)
((ADXL345Listener) en.nextElement()).XAccelChange(e);
}
case Y_AXIS: {
for (Enumeration en = listeners.elements(); en.hasMoreElements();)
((ADXL345Listener) en.nextElement()).YAccelChange(e);
}
case Z_AXIS: {
for (Enumeration en = listeners.elements(); en.hasMoreElements();)
((ADXL345Listener) en.nextElement()).ZAccelChange(e);
}
}
}
}
| 30.346667 | 82 | 0.638401 |
9a9ddbcf87f6eacddf09b3ac08f750b7aa4824fa | 4,914 | package utils;
import java.util.Random;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.*;
/**
* Some simple utilities for writing tests.
*
* @author Samuel A. Rebelsky
*/
public class TestUtils {
// +--------+------------------------------------------------------
// | Fields |
// +--------+
static Random rand = new Random();
// +---------+-----------------------------------------------------
// | Methods |
// +---------+
/**
* Append a bunch of values to an ArrayList. (This probably exists
* somewhere, but I'm too lazy to find it.)
*/
public static <T> void appendValues(ArrayList<T> lst, T[] values) {
for (T val : values) {
lst.add(val);
} // for
} // appendValues
/**
* Check that the values return by it are the values in expected
*/
public static <T> void checkIterator(T[] expected, Iterator<T> it,
Supplier<String> message) {
for (int i = 0; i < expected.length; i++) {
assertTrue(it.hasNext(), message);
assertEquals(expected[i], it.next(), message);
} // for
assertFalse(it.hasNext(), message);
} // checkIterator
public static <T> void checkIterator(T[] expected, Iterator<T> it,
String message) {
checkIterator(expected, it, () -> message);
} // checkIterator(T[], Iterator<T>, String)
public static <T> void checkIterator(T[] expected, Iterator<T> it) {
checkIterator(expected, it, () -> "");
} // checkIterator(T[], Iterator<T>)
public static void checkIterator(int[] expected, Iterator<Integer> it) {
for (int i = 0; i < expected.length; i++) {
assertTrue(it.hasNext(), "position " + i);
assertEquals(expected[i], (int) it.next(), "postition " + i);
} // checkIterator
assertFalse(it.hasNext());
} // checKIterator
/**
* Return a predicate that holds when its parameter is less than n.
*/
public static Predicate<Integer> lessThan(int n) {
return (i) -> i < n;
} // lessThan
/**
* Return a predicate that holds when its parameter is greater than n.
*/
public static Predicate<Integer> greaterThan(int n) {
return (i) -> i > n;
} // greaterThan
/**
* Create an ArrayList with an array of values. (This probably exists somewhere, but I can't find
* it.)
*/
public static ArrayList<Integer> makeList(int[] values) {
ArrayList<Integer> result = new ArrayList<Integer>(values.length);
for (int val : values) {
result.add(val);
} // for
return result;
} // makeList
/**
* Create an unpredictable array of integers in non-decreasing order.
*/
public static int[] randomInts(int size) {
int[] result = new int[size];
result[0] = 50 - rand.nextInt(100);
for (int i = 1; i < size; i++) {
result[i] = result[i-1] + rand.nextInt(3);
} // for
return result;
} // randomInts(int)
/**
* Randomly permute an array.
*/
public static <T> void randomlyPermute(T[] values) {
for (int i = 0; i < values.length; i++) {
TestUtils.swap(values, i, rand.nextInt(values.length));
} // for
} // randomlyPermute(T[])
/**
* Randomly permute an array of integers
*/
public static void randomlyPermute(int[] values) {
for (int i = 0; i < values.length; i++) {
TestUtils.swap(values, i, rand.nextInt(values.length));
} // for
} // randomlyPermute
/**
* Create an ArrayList with values from lb (inclusive) to ub (exclusive).
*/
public static ArrayList<Integer> range(int lb, int ub) {
ArrayList<Integer> result = new ArrayList<Integer>(ub - lb);
for (int i = lb; i < ub; i++) {
result.add(i);
} // for
return result;
} // range(int, int)
/**
* Remove all the values that meet a predicate.
*/
public static <T> void remove(Iterable<? extends T> values,
Predicate<? super T> pred) {
remove(values.iterator(), pred);
} // remove(Iterable, Predicate)
/**
* Remove all the values the meet a predicate
*/
public static <T> void remove(Iterator<? extends T> it,
Predicate<? super T> pred) {
while (it.hasNext()) {
if (pred.test(it.next())) {
it.remove();
} // if
} // while
} // remove
/**
* Remove all the values associated with an iterator.
*/
public static <T> void removeAll(Iterator<T> it) {
while (it.hasNext()) {
it.next();
it.remove();
} // while
} // removeAll
/**
* Swap two values in an array.
*/
public static <T> void swap(T[] values, int i, int j) {
T temp = values[i];
values[i] = values[j];
values[j] = temp;
} // swap
public static void swap(int[] values, int i, int j) {
int temp = values[i];
values[i] = values[j];
values[j] = temp;
} // swap
} // TestUtils
| 26.706522 | 99 | 0.582621 |
55ca79866d5c92f66f973c765d55e68c8a2cdf1a | 492 | package com.airback.vaadin.ui;
import com.airback.vaadin.web.ui.WebThemes;
import com.vaadin.ui.Component;
import com.vaadin.ui.Panel;
/**
* @author airback Ltd
* @since 7.0.0
*/
public class FormSection extends Panel {
public FormSection(String caption) {
this(caption, null);
}
public FormSection(String caption, Component content) {
super(caption, content);
this.addStyleName(WebThemes.FORM_SECTION);
UIUtils.makeStackPanel(this);
}
}
| 22.363636 | 59 | 0.689024 |
c60a5c6523019f4c32ffcaa418d71caf8a6fd934 | 509 | package equals;
import java.util.Objects;
class Person{
private String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
// 우클릭 - 소스 - generate hashCode() and equals()클릭
}
public class App {
public static void main(String[] args) {
// 같은지 비교하는 메소드
Person p1 = new Person("펭수");
Person p2 = new Person("펭수"); // p1과 p2는 이름은 같지만 다른 객체
System.out.println(p1 == p2); // false
System.out.println(p1.equals(p2)); // true
}
}
| 16.966667 | 56 | 0.646365 |
319e24ea962054193c0015c5a0fdc0a8a4d73c86 | 11,861 | package com.example.org.bouncycastle.crypto.signers;
import java.security.DigestException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
import java.text.ParseException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.xml.bind.DatatypeConverter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.RSASSAVerifier;
import com.nimbusds.jose.util.Base64URL;
/**
* <p> Test harness to validate RSA-PSS-MGF1 Scheme. </p>
* @author rhasyagar
* @since 05-Nov-2018
*
*/
public class TestJWS_POC {
public static final String RSA_ENCRYPT_CIPHER_TRANSFORMATION = "RSA/ECB/NoPadding";
public static final String RSA_SIGNATURE_SHA256_ALGORITHM = "SHA256withRSA";
public static final String RSA_SIGNATURE_SHA256_AND_MGF1_ALGORITHM = "SHA256withRSAandMGF1";
public static final String SHA256_MESSAGE_DIGEST_ALGORITHM_NAME= "SHA-256";
static {
Security.addProvider(new BouncyCastleProvider());
System.setProperty(KeystoreHandler.SYSTEM_PROPERTY_KEY__PKCS11_CONFIG_FILE_PATH, "C:\\Ravi-2018\\Data\\java\\Nitro-HSM\\nitrohsm-sunpkcs11.cfg");
}
public static void main(String[] args) {
TestJWS_POC testJWS = new TestJWS_POC();
String privateKeyAlias = "hvr-nitro-key-hsm-rsa-test";
String jsonString = "{1:2}";
String serializedJWSString = testJWS.handleJWSSign(jsonString, privateKeyAlias);
boolean validationStatus = testJWS.handleJWSValidate(serializedJWSString, privateKeyAlias);
System.out.println("Validation Status : "+validationStatus);
// testJWS.handleJWSSignTwo(jsonString, privateKeyAlias);
// testJWS.handleJWSSignThree(jsonString, privateKeyAlias);
char[] modifiedJWSString = serializedJWSString.toCharArray();
modifiedJWSString[modifiedJWSString.length-10] = '0';
boolean validationStatusModified = testJWS.handleJWSValidate(new String(modifiedJWSString), privateKeyAlias);
System.out.println("Validation Status Modified: "+validationStatusModified);
}
private PrivateKey fetchPrivateKeyFromHSM(String alias) {
KeystoreHandler keystoreHandler = KeystoreHandler.obtainClassInstance();
PrivateKey privateKey = keystoreHandler.obtainPrivateKey(alias);
return privateKey;
}
/*
Enter password
******
Keystore Class :class java.security.KeyStore
Fetching private key from provider :SunPKCS11-SunPKCS11-NitroHSM
Fetching private key from provider :SunPKCS11-SunPKCS11-NitroHSM
Modulus Bit Length :2048
Signing Input :eyJhbGciOiJQUzI1NiJ9.ezE6Mn0
class sun.security.pkcs11.P11Key$P11PrivateKey
PrivateKeyEncoded :null
Block Length :256
SignedInfo :HeEwJtEhu4X0aM/4ki/BEM5SWOcDu6/WvtUUr1mGCsqs5WnW0e88OMZueWGQV5ZTed86bMmnYKVuC6Mn+kPm+Tx6dhnZrHV+379/aQ+X9ApOr55G0RaXjJNTPAWlKSyAA/XLQfceEvXo+RFCVRagpj3M05//msZNIyiNrT1qpW0tEaIlApDc08CEAIXOXfCfSv0Em022PiAQpnvBqJx6xCl+NO9jrlYxHnTRxwd38CSXIfwGQbKLeiTOvefk9veGkbnDRAxlfO9tkvqPtakcvhU5W79cmnEThrAMGp496xbR35ifEFQ4h+/Uod6x5o/A7Abb7zElmaRUGo8EQ2Zf6A==
Fetching private key from provider :SunPKCS11-SunPKCS11-NitroHSM
Verification Status :true
Validation Status : true
Fetching private key from provider :SunPKCS11-SunPKCS11-NitroHSM
Verification Status :false
Validation Status Modified: false
*/
/**
* @param jsonString
* @param privateKeyAlias
*/
private String handleJWSSign(String jsonString, String privateKeyAlias) {
JWSHeader header = new JWSHeader(JWSAlgorithm.PS256);
Payload payload = new Payload(jsonString);
JWSObject jwsObject = new JWSObject(header, payload);
PrivateKey privateKey = fetchPrivateKeyFromHSM(privateKeyAlias);
Certificate certificate = KeystoreHandler.obtainClassInstance().obtainPublicKey(privateKeyAlias);
// X509Certificate x509Certificate = (X509Certificate) certificate;
RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey();
int modulusBitLength = rsaPublicKey.getModulus().bitLength();
// RSASSASigner rsassaSigner = new RSASSASigner(privateKey);
// rsassaSigner.getJCAContext().setProvider(KeystoreHandler.obtainClassInstance().fetchProvider());
byte[] signingInput = jwsObject.getSigningInput();
String signingInputStr = new String(signingInput);
System.out.println("Modulus Bit Length :"+modulusBitLength);
System.out.println("Signing Input :"+signingInputStr);
/*
try {
jwsObject.sign(rsassaSigner);
} catch (JOSEException e) {
e.printStackTrace();
}
*/
// String signedJWS = jwsObject.serialize();
// System.out.println(signedJWS);
MessageDigest contentDigest = null;
MessageDigest mgfDigest = null;
int saltLength = -1;
Cipher cipher = null;
byte[] signedInfo = null;
try {
contentDigest = MessageDigest.getInstance(SHA256_MESSAGE_DIGEST_ALGORITHM_NAME);
mgfDigest = MessageDigest.getInstance(SHA256_MESSAGE_DIGEST_ALGORITHM_NAME);
saltLength = mgfDigest.getDigestLength();
cipher = Cipher.getInstance(RSA_ENCRYPT_CIPHER_TRANSFORMATION, KeystoreHandler.obtainClassInstance().fetchProvider());
PSSSigningBCCustomUtility_POC pssSigningBCCustomUtility_Source = new PSSSigningBCCustomUtility_POC(cipher, contentDigest, mgfDigest, saltLength);
System.out.println(privateKey.getClass());
System.out.println("PrivateKeyEncoded :"+privateKey.getEncoded());
pssSigningBCCustomUtility_Source.init(true, null, null, privateKey, modulusBitLength);
pssSigningBCCustomUtility_Source.update(signingInput, 0, signingInput.length);
signedInfo = pssSigningBCCustomUtility_Source.generateSignature();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (DigestException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
System.out.println("SignedInfo :"+DatatypeConverter.printBase64Binary(signedInfo));
Base64URL base64urlSignedInfo = Base64URL.encode(signedInfo);
String serializedJWSObject = buildSignedJWSString(signingInputStr, base64urlSignedInfo.toString());
JWSObject jwsObjectTwo=null;
String result = null;
try {
jwsObjectTwo = JWSObject.parse(serializedJWSObject);
result = jwsObjectTwo.serialize();
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
private String buildSignedJWSString(String signingInput, String base64EncodedSignature) {
StringBuilder jwsSignedInfo = new StringBuilder();
jwsSignedInfo.append(signingInput);
jwsSignedInfo.append(".");
jwsSignedInfo.append(base64EncodedSignature);
return jwsSignedInfo.toString();
}
/*
java.security.InvalidAlgorithmParameterException: Parameters not supported
at sun.security.pkcs11.P11RSACipher.engineInit(P11RSACipher.java:177)
at javax.crypto.Cipher.init(Cipher.java:1393)
at javax.crypto.Cipher.init(Cipher.java:1326)
at com.example.jws.test.TestJWS.handleJWSSignTwo(TestJWS.java:169)
*/
/**
* @deprecated
* @param jsonString
* @param privateKeyAlias
*/
private void handleJWSSignTwo(String jsonString, String privateKeyAlias) {
JWSHeader header = new JWSHeader(JWSAlgorithm.PS256);
Payload payload = new Payload(jsonString);
JWSObject jwsObject = new JWSObject(header, payload);
PrivateKey privateKey = fetchPrivateKeyFromHSM(privateKeyAlias);
byte[] signingInput = jwsObject.getSigningInput();
System.out.println("Signing Input :"+new String(signingInput));
Cipher cipher = null;
byte[] signedInfo = null;
try {
cipher = Cipher.getInstance(RSA_ENCRYPT_CIPHER_TRANSFORMATION, KeystoreHandler.obtainClassInstance().fetchProvider());
PSSParameterSpec pssParameterSpec = new PSSParameterSpec("SHA256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1);
cipher.init(Cipher.ENCRYPT_MODE, privateKey, pssParameterSpec);
signedInfo = cipher.doFinal(signingInput);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
System.out.println("SignedInfo :"+DatatypeConverter.printBase64Binary(signedInfo));
}
/*
Exception in thread "main" java.lang.UnsupportedOperationException
at java.security.SignatureSpi.engineSetParameter(SignatureSpi.java:324)
at java.security.Signature$Delegate.engineSetParameter(Signature.java:1240)
at java.security.Signature.setParameter(Signature.java:870)
at com.example.jws.test.TestJWS.handleJWSSignThree(TestJWS.java:196)
*/
/**
* @deprecated
*/
private void handleJWSSignThree(String jsonString, String privateKeyAlias) {
JWSHeader header = new JWSHeader(JWSAlgorithm.PS256);
Payload payload = new Payload(jsonString);
JWSObject jwsObject = new JWSObject(header, payload);
PrivateKey privateKey = fetchPrivateKeyFromHSM(privateKeyAlias);
byte[] signingInput = jwsObject.getSigningInput();
System.out.println("Signing Input :"+new String(signingInput));
Signature signature = null;
byte[] signedInfo = null;
try {
signature = Signature.getInstance(RSA_SIGNATURE_SHA256_ALGORITHM, KeystoreHandler.obtainClassInstance().fetchProvider());
PSSParameterSpec pssParameterSpec = new PSSParameterSpec("SHA256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1);
signature.setParameter(pssParameterSpec);
signature.initSign(privateKey);
signature.update(signingInput);
signedInfo = signature.sign();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
}
System.out.println("SignedInfo :"+DatatypeConverter.printBase64Binary(signedInfo));
}
private boolean handleJWSValidate(String serializedJWS, String certificateAlias) {
boolean result = false;
try {
JWSObject jwsObject = JWSObject.parse(serializedJWS);
Certificate certificate = KeystoreHandler.obtainClassInstance().obtainPublicKey(certificateAlias);
RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey();
RSASSAVerifier rsassaVerifier = new RSASSAVerifier(rsaPublicKey);
rsassaVerifier.getJCAContext().setProvider(new BouncyCastleProvider());
result = jwsObject.verify(rsassaVerifier);
System.out.println("Verification Status :"+result);
} catch (ParseException e) {
e.printStackTrace();
} catch (JOSEException e) {
e.printStackTrace();
}
return result;
}
}
| 37.065625 | 357 | 0.760054 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.