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
|
---|---|---|---|---|---|
a9eb5a89bb7e7e3a78fd05bd213d35a335f2ca5a | 6,033 | package team.unstudio.udpl.item;
import com.google.common.collect.Lists;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import java.util.*;
public class ItemWrapper {
public static ItemWrapper newItemWrapper() {
return new ItemWrapper();
}
public static ItemWrapper newItemWrapper(Material type) {
return new ItemWrapper(type);
}
public static ItemWrapper newItemWrapper(Material type, int amount) {
return new ItemWrapper(type, amount);
}
public static ItemWrapper newItemWrapper(Material type, int amount, short damage) {
return new ItemWrapper(type, amount, damage);
}
public static ItemWrapper newItemWrapper(ItemStack itemStack) {
return new ItemWrapper(itemStack);
}
private final ItemStack itemStack;
public ItemWrapper() {
this(new ItemStack(Material.AIR));
}
public ItemWrapper(Material type) {
this(new ItemStack(type));
}
public ItemWrapper(Material type, int amount) {
this(new ItemStack(type, amount));
}
public ItemWrapper(Material type, int amount, short damage) {
this(new ItemStack(type, amount, damage));
}
public ItemWrapper(ItemStack itemStack) {
this.itemStack = itemStack.clone();
}
public Material getType() {
return itemStack.getType();
}
public ItemWrapper setType(Material type) {
itemStack.setType(type);
return this;
}
public short getDurability() {
return itemStack.getDurability();
}
public ItemWrapper setDurability(short durability) {
itemStack.setDurability(durability);
return this;
}
public int getAmount() {
return itemStack.getAmount();
}
public ItemWrapper setAmount(int amount) {
itemStack.setAmount(amount);
return this;
}
public boolean hasItemMeta() {
return itemStack.hasItemMeta();
}
public String getDisplayName() {
ItemMeta meta = itemStack.getItemMeta();
return meta.hasDisplayName() ? meta.getDisplayName() : "";
}
public boolean hasDisplayName() {
return itemStack.getItemMeta().hasDisplayName();
}
public ItemWrapper setDisplayName(String name) {
ItemMeta meta = itemStack.getItemMeta();
meta.setDisplayName(name);
itemStack.setItemMeta(meta);
return this;
}
public String getLocalizedName() {
ItemMeta meta = itemStack.getItemMeta();
return meta.hasLocalizedName() ? meta.getLocalizedName() : "";
}
public boolean hasLocalizedName() {
return itemStack.getItemMeta().hasLocalizedName();
}
public ItemWrapper setLocalizedName(String name) {
ItemMeta meta = itemStack.getItemMeta();
meta.setLocalizedName(name);
itemStack.setItemMeta(meta);
return this;
}
public List<String> getLore() {
ItemMeta meta = itemStack.getItemMeta();
if (meta.hasLore())
return meta.getLore();
else
return Lists.newArrayList();
}
public boolean hasLore() {
return itemStack.getItemMeta().hasLore();
}
public ItemWrapper setLore(String... lore) {
setLore(Arrays.asList(lore));
return this;
}
public ItemWrapper setLore(List<String> lore) {
itemStack.getItemMeta().setLore(lore);
return this;
}
public ItemWrapper addLore(String... lore) {
List<String> lores = getLore();
Collections.addAll(lores, lore);
setLore(lores);
return this;
}
public ItemWrapper addLore(int index, String... lore) {
List<String> lores = getLore();
lores.addAll(index, Arrays.asList(lore));
setLore(lores);
return this;
}
public ItemWrapper removeLore(int index) {
List<String> lores = getLore();
lores.remove(index);
setLore(lores);
return this;
}
public ItemWrapper removeLore(String regex) {
List<String> lores = getLore();
for (String s : lores) {
if (s.matches(regex))
lores.remove(s);
}
setLore(lores);
return this;
}
public Map<Enchantment, Integer> getEnchantments() {
return itemStack.getEnchantments();
}
public boolean hasEnchantment(Enchantment ench) {
return itemStack.containsEnchantment(ench);
}
public int getEnchantmentLevel(Enchantment ench) {
return itemStack.getEnchantmentLevel(ench);
}
public ItemWrapper addEnchantment(Enchantment ench, int level) {
itemStack.addEnchantment(ench, level);
return this;
}
public ItemWrapper addUnsafeEnchantment(Enchantment ench, int level) {
itemStack.addUnsafeEnchantment(ench, level);
return this;
}
public ItemWrapper removeEnchantment(Enchantment ench) {
itemStack.removeEnchantment(ench);
return this;
}
public Set<ItemFlag> getItemFlags() {
return itemStack.getItemMeta().getItemFlags();
}
public boolean hasItemFlag(ItemFlag flag) {
return itemStack.getItemMeta().hasItemFlag(flag);
}
public ItemWrapper addItemFlags(ItemFlag... flags) {
ItemMeta meta = itemStack.getItemMeta();
meta.addItemFlags(flags);
itemStack.setItemMeta(meta);
return this;
}
public ItemWrapper removeItemFlags(ItemFlag... flags) {
ItemMeta meta = itemStack.getItemMeta();
meta.removeItemFlags(flags);
itemStack.setItemMeta(meta);
return this;
}
public boolean isUnbreakable() {
return itemStack.getItemMeta().isUnbreakable();
}
public ItemWrapper setUnbreakable(boolean value) {
ItemMeta meta = itemStack.getItemMeta();
meta.setUnbreakable(value);
itemStack.setItemMeta(meta);
return this;
}
public ItemMeta getItemMeta() {
return itemStack.getItemMeta();
}
@SuppressWarnings("unchecked")
public <T extends ItemMeta> Optional<T> getItemMeta(Class<T> clazz) {
ItemMeta itemMeta = getItemMeta();
return itemMeta != null && clazz.isAssignableFrom(itemMeta.getClass()) ? Optional.of((T)itemMeta) : Optional.empty();
}
public ItemWrapper setItemMeta(ItemMeta itemMeta) {
itemStack.setItemMeta(itemMeta);
return this;
}
public ItemStack get() {
return itemStack.clone();
}
}
| 24.035857 | 120 | 0.704127 |
4e928423030a59912886aacdb244c32e9970326d | 10,763 | package com.kovacs.swashbuckler;
import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferStrategy;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.JFrame;
import com.kovacs.swashbuckler.game.Board;
import com.kovacs.swashbuckler.game.BoardCoordinate;
import com.kovacs.swashbuckler.game.Plan;
import com.kovacs.swashbuckler.game.entity.Entity;
import com.kovacs.swashbuckler.game.entity.Entity.EntityType;
import com.kovacs.swashbuckler.game.entity.Pirate;
import com.kovacs.swashbuckler.game.entity.Shelf;
import com.kovacs.swashbuckler.game.entity.Table;
import com.kovacs.swashbuckler3.Engine;
/*
* The class that controls graphical interactions on the client side.
*/
public class ClientGUI extends Canvas
{
private static final long serialVersionUID = 495654254622340673L;
/*
* The dimensions of the window in virtual pixels.
*/
public static final double VIRTUAL_WIDTH = 1280.0, VIRTUAL_HEIGHT = 720.0;
/*
* The maximum length of a message in the output area.
*/
public static final int MAX_MESSAGE_LENGTH_LARGE = 27;
public static final int MAX_MESSAGE_LENGTH_SMALL = 54;
/*
* Keeps track of the text size setting.
*/
// TODO: make it so that the user can adjust this.
private static final boolean largeText = false;
/*
* Default colors for things. //TODO: these will probably go away
* eventually.
*/
private static final Color backgroundColor = Color.BLACK, foregroundColor = new Color(0x666666),
redTint = new Color(255, 0, 0, 100), greenTint = new Color(0, 255, 0, 100),
yellowTint = new Color(255, 255, 0, 100);
/*
* A list of recent messages to display.
*/
public LinkedList<String> messageHistory;
/*
* A queue of messages that have not been added to the output window, but
* have been written to the gui.
*/
private Queue<Character> pendingCharacters;
/*
* The maximum number of messages that can fit on the screen.
*/
private static final int MAX_MESSAGES_LARGE = 47;
private static final int MAX_MESSAGES_SMALL = 82;
/*
* The main window of the gui.
*/
public JFrame frame;
/*
* The mouse input adapter.
*/
private MouseInput mouseInput;
/*
* The keyboard input adapter.
*/
public KeyboardInput keyboardInput;
/*
* An instance of a board that is given to the client by the server on board
* updates.
*/
public Board board;
/*
* The thread that adds the characters to the output slowly.
*/
private Thread characterAdder;
/*
* The thing that pops up when you click.
*/
public Menu menu;
/*
* Keeps track of how big the window is.
*/
private double scale;
public ClientGUI()
{
messageHistory = new LinkedList<>();
for (int i = 0; i < (largeText ? MAX_MESSAGES_LARGE : MAX_MESSAGES_SMALL); i++)
messageHistory.add("");
pendingCharacters = new LinkedList<>();
frame = new JFrame("Swashbuckler");
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
setPreferredSize(new Dimension((int) VIRTUAL_WIDTH, (int) VIRTUAL_HEIGHT));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new Thread()
{
@Override
public void run()
{
while (true)
{
draw();
try
{
Thread.sleep(2);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}.start();
resize(1);
startCharacterAdder();
menu = new Menu();
keyboardInput = new KeyboardInput();
mouseInput = new MouseInput();
addMouseListener(mouseInput);
addMouseMotionListener(mouseInput);
addKeyListener(keyboardInput);
}
/*
* Creates the graphics object and draws everything on it.
*/
public void draw()
{
BufferStrategy bs = getBufferStrategy();
if (bs == null)
{
createBufferStrategy(2);
requestFocus();
return;
}
Graphics graphics = bs.getDrawGraphics();
Graphics2D g = (Graphics2D) graphics;
AffineTransform at = new AffineTransform();
double scale = getWidth() / (double) VIRTUAL_WIDTH;
at.scale(scale, scale);
g.setTransform(at);
g.setColor(backgroundColor);
g.fillRect(0, 0, (int) VIRTUAL_WIDTH, (int) VIRTUAL_HEIGHT);
drawPlanHistory(g);
drawEvents(g);
drawBoard(g);
drawOtherStuff(g);
bs.show();
g.dispose();
}
/*
* Prints a message to the output area and shifts/aligns everything
* accordingly.
*/
public void writeMessage(String message)
{
while (message.length() > (largeText ? MAX_MESSAGE_LENGTH_LARGE : MAX_MESSAGE_LENGTH_SMALL))
{
int endIndex = largeText ? MAX_MESSAGE_LENGTH_LARGE : MAX_MESSAGE_LENGTH_SMALL;
while (!Character.isWhitespace(message.charAt(endIndex)))
endIndex--;
writeMessage(message.substring(0, endIndex));
message = " " + message.substring(endIndex);
}
pendingCharacters.add('\n');
for (int i = 0; i < message.length(); i++)
pendingCharacters.add(message.charAt(i));
if (!characterAdder.isAlive())
startCharacterAdder();
}
/*
* TODO: comment here. Change the method name. Do something.
*/
private void drawOtherStuff(Graphics g)
{
;
}
/*
* Draws the event window.
*/
private void drawEvents(Graphics2D g)
{
g.setPaint(new GradientPaint(0, 0, backgroundColor, 0, 320, foregroundColor));
g.fillRect(8, 20, 328, (largeText ? 658 : 664));
g.setColor(foregroundColor);
g.fillRect(8, (largeText ? 682 : 688), 328, (largeText ? 18 : 12));
g.setColor(backgroundColor);
for (int i = 0; i < (largeText ? MAX_MESSAGES_LARGE : MAX_MESSAGES_SMALL); i++)
TextDrawer.drawText(g, messageHistory.get(i), 12, (largeText ? 18 : 24) + (largeText ? 14 : 8) * i,
largeText ? 2 : 1);
TextDrawer.drawText(g, keyboardInput.keyboardInput, 12, largeText ? 686 : 692, largeText ? 2 : 1);
}
/*
* Draws the right-side area (plot window).
*/
private void drawPlanHistory(Graphics g)
{
// TODO: only draw the clickable stuff and only allow clicks if the game
// is ready for that type of click.
if (ClientMain.main.getSelectedPirate() == null)
return;
// TODO: decide on and standardize how everyone knows what pirates exist
// and where their plan histories are stored.
if (!ClientMain.main.getOwnedPirateNames().contains(ClientMain.main.getSelectedPirate().getName()))
return;
// TODO: control access to things so that I don't have to keep typing
// ClientMain.main.gui and such
// draw background
g.setColor(foregroundColor);
g.fillRect(988, 104, 284, 596);
// tint future turns red
g.setColor(redTint);
g.fillRect(1000, 156 + ClientMain.main.currentTurn * 36, 260, 532 - ClientMain.main.currentTurn * 36);
// tint the current turn
if (ClientMain.main.getPlanInProgress().isLocked())
g.setColor(greenTint);
else
g.setColor(yellowTint);
g.fillRect(1000, 120 + ClientMain.main.currentTurn * 36, 260, 28);
// draw all the boxes
g.setColor(backgroundColor);
for (int i = 0; i < 7; i++)
g.fillRect(996 + i * 44, 112, 4, 580);
for (int i = 0; i < 16; i++)
g.fillRect(996, 112 + i * 36, 268, 8);
g.fillRect(996, 688, 268, 4);
for (int i = 0; i < 6; i++)
g.drawRect(1000 + i * 44, 116, 40, 36);
for (int i = 1; i <= 6; i++)
TextDrawer.drawText(g, "" + i, 1010 + (i - 1) * 44, 124, 4);
// fill in the plan history
for (int turn = 0; turn < Engine.MAX_TURNS; turn++)
{
if (ClientMain.main.getSelectedPirate() == null)
return;
Plan plan = ClientMain.main.planHistory.get(ClientMain.main.getSelectedPirate().getName())[turn];
if (plan == null)
continue;
for (int i = 0; i < plan.getOrders().length; i++)
TextDrawer.drawText(g, plan.getOrders()[i].getAbbreviation(), 1003 + i * 44, 128 + 36 * turn, 2);
}
// draw the submit button
g.setColor(foregroundColor);
g.fillRect(988, 64, 124, 32);
g.setColor(backgroundColor);
TextDrawer.drawText(g, "Submit", 998, 72, 3);
}
/*
* Draws the board.
*/
private void drawBoard(Graphics g)
{
if (board == null)
return;
g.drawImage(Images.tavernFloor, 344, 20, 636, 680, null);
for (Entity entity : board.allEntities(Entity.class))
for (BoardCoordinate coordinate : entity.coordinates)
{
int xDrawPosition = (coordinate.number - 1) * 44 + 355;
int yDrawPosition = (coordinate.letter - 'a') * 44 + 31;
if (entity.type == EntityType.TABLE)
g.drawImage(((Table) entity).getDrawImage(coordinate), xDrawPosition, yDrawPosition, 42, 42, null);
else if (entity.type == EntityType.SHELF)
g.drawImage(((Shelf) entity).getDrawImage(coordinate), xDrawPosition, yDrawPosition, 42, 42, null);
else if (entity.type == EntityType.PIRATE && ClientMain.main.getSelectedPirate() == (Pirate) entity)
{
((Graphics2D) g).setStroke(new BasicStroke(2));
g.setColor(Color.YELLOW);
g.drawRect(xDrawPosition - 1, yDrawPosition - 1, 44, 44);
g.drawImage(entity.getImage(), xDrawPosition, yDrawPosition, 42, 42, null);
}
else
g.drawImage(entity.getImage(), xDrawPosition, yDrawPosition, 42, 42, null);
}
}
/*
* Resizes the window. Scale of 1 sets it to the default.
*/
public void resize(double scale)
{
if (scale < .1)
scale = .1;
this.scale = scale;
setPreferredSize(new Dimension((int) (scale * VIRTUAL_WIDTH), (int) (scale * VIRTUAL_HEIGHT)));
setSize(new Dimension((int) (scale * VIRTUAL_WIDTH), (int) (scale * VIRTUAL_HEIGHT)));
frame.pack();
}
/*
* Adds a single character to the output window. Messages are written in and
* stored in a queue, then popped off one letter at a time into the output.
*/
private void addCharacterToOutput()
{
try
{
char nextChar = pendingCharacters.poll();
if (nextChar == '\n')
{
messageHistory.poll();
messageHistory.add("");
}
else
{
messageHistory.set((largeText ? MAX_MESSAGES_LARGE : MAX_MESSAGES_SMALL) - 1, messageHistory
.get((largeText ? MAX_MESSAGES_LARGE : MAX_MESSAGES_SMALL) - 1).concat(nextChar + ""));
}
}
catch (NullPointerException e)
{
System.err.println("Null pointer from the character thread.");
try
{
characterAdder.join();
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
}
}
/*
* Restarts the character adder thread.
*/
private void startCharacterAdder()
{
characterAdder = new Thread()
{
@Override
public void run()
{
while (!pendingCharacters.isEmpty())
{
addCharacterToOutput();
try
{
Thread.sleep(4);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
characterAdder.start();
}
public double getScale()
{
return scale;
}
} | 27.597436 | 104 | 0.679829 |
830e652729b653046d948017f1189d31926cc139 | 22,527 |
package org.firstinspires.ftc.teamcode;
import android.app.Activity;
import android.view.View;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsAnalogOpticalDistanceSensor;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cColorSensor;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cGyro;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cRangeSensor;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorController;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.DeviceInterfaceModule;
import com.qualcomm.robotcore.hardware.OpticalDistanceSensor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.hardware.ServoController;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
import org.firstinspires.ftc.teamcode.safehardware.DummyOpticalDistanceSensor;
import org.firstinspires.ftc.teamcode.safehardware.DummyServo;
import static org.firstinspires.ftc.teamcode.R.layout.servo;
@Autonomous(name = "DRSS RedAutonomous", group = "DRSS")
public class DRSS_RedAutonomous extends LinearOpMode{
private DcMotor leftMotor = null;
private DcMotor rightMotor = null;
private DcMotor particleAccelerator = null;
private DcMotor particleLift = null;
//Declare all motors being used
private DcMotorController driveMotorController = null;
private DcMotorController shooterMotorController = null;
//Declare all motor controllers being used
private CRServo pushRod = null;
private Servo cannonSeal = null;
//Declare the a CRSevo for the push rod on the back of the robot
private ServoController servoController = null;
//Declare a servo controller
private OpticalDistanceSensor opticalDistanceSensor = null;
private ModernRoboticsI2cColorSensor colorSensor = null;
private ModernRoboticsI2cGyro gyro = null;
//Declare the gyro and color sensor we will be using
private ElapsedTime runTime = new ElapsedTime(ElapsedTime.Resolution.MILLISECONDS);
/*Create a new instance of runTime with a resolution of milliseconds.
*We don't need nanosecond precision
*/
private boolean isFinished = false;
//Declare a boolean stating if the robot has completed its route
private boolean resetRequested = true;
//Declare a boolean stating if a reset cycle has been requested
private int heading;
//Declare an integer holding the heading of the gyro
private int red, green, blue, alpha = 0;
//Declare integers for each of the color channels for the gyro
private int lTarget;
private int rTarget;
//Only used for deprecated versions of the turn() method.
private int target;
//Declare an integer to contain the target encoder position when driving straight
private int gyroTarget;
//Declare an integer to contain the target gyro position when turning
private int currentStep = 1;
//Declare an integer to contain which the step the robot is currently running
private int error;
//Only used for future proportional control logic when driving forward.
public void runOpMode() throws InterruptedException {
telemetry.addData("Status", "Initializing");
//Output that the robot is initializing.
try {
leftMotor = hardwareMap.dcMotor.get("leftMotor");
leftMotor.setDirection(DcMotor.Direction.FORWARD);
leftMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
} catch (Exception eTopMotor) {
leftMotor = null;
}
try {
rightMotor = hardwareMap.dcMotor.get("rightMotor");
rightMotor.setDirection(DcMotor.Direction.REVERSE);
rightMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
} catch (Exception eBottomMotor) {
rightMotor = null;
}
try {
colorSensor = (ModernRoboticsI2cColorSensor) hardwareMap.colorSensor.get("colorSensor");
} catch (Exception eColorSensor) {
colorSensor = null;
telemetry.addData("Warning: ", "Color Sensor could not be found");
}
try {
driveMotorController = hardwareMap.dcMotorController.get("DriveMotorController");
} catch (Exception eDriveController) {
driveMotorController = null;
}
try{
particleAccelerator = hardwareMap.dcMotor.get("particleAccelerator");
} catch (Exception eParticleAccelerator){
particleAccelerator = null;
}
try{
particleLift = hardwareMap.dcMotor.get("particleLift");
} catch ( Exception eParticleLift){
particleLift = null;
}
try{
shooterMotorController = hardwareMap.dcMotorController.get("ShooterMotorController");
} catch(Exception eShooterController){
shooterMotorController = null;
}
try {
gyro = (ModernRoboticsI2cGyro) hardwareMap.gyroSensor.get("gyro");
} catch (Exception eGyroSensor) {
gyro = null;
}
try{
pushRod = hardwareMap.crservo.get("pushRod");
} catch ( Exception ePushRod){
pushRod = null;
}
try{
servoController = hardwareMap.servoController.get("servoController");
} catch(Exception eServoController){
servoController = null;
}
try{
cannonSeal = hardwareMap.servo.get("cannonSeal");
} catch(Exception eCannonSeal){
telemetry.addData("Exception ", "cannonSeal not found");
cannonSeal = new DummyServo();
}
try{
opticalDistanceSensor = hardwareMap.opticalDistanceSensor.get("opticalSensor");
} catch(Exception eOpticalDistanceSensor){
telemetry.addData("Excpetion ", "opticalSensor not found");
opticalDistanceSensor = new DummyOpticalDistanceSensor();
}
if(pushRod != null) {
pushRod.setPower(-1.0);
//If the push rod is assigned, suck it into the robot
}
if (gyro != null) {
gyro.calibrate();
while (gyro.isCalibrating()) {
Thread.sleep(50);
idle();
//If the gyro is assigned, calibrate and do not do anything else until it finishes
}
telemetry.addData(">", "Gyro Calibrated. Press Start.");
} else {
telemetry.addData("ERROR", "GYRO NOT INTIALIZED");
//If the gyro is not assigned, declare so.
}
telemetry.addData(">", "Gyro Calibrated. Press Start.");
telemetry.update();
//Send telemetry data to robot controller
waitForStart();
//Do not run the following code until that start button is pressed.
while (!isFinished && !isStopRequested()) {
/* Do the following until the robot finishes its autonomous route or a stop
* has been requested by the robot controller
*/
telemetry.update();
//Send telemetry data to the robot controller
heading = gyro.getHeading();
heading--;
/* Get the heading (essentialy degrees rotation on the z, or veritical axis) from the
* gyro. The gyro increments the heading by one degree each time it is read, so the
* variable storing the heading decrements by one degree each time it is assigned.
*/
if(resetRequested){
reset();
resetRequested = false;
/* If a reset is requested, reset all motor encoders, the gyro heading, and the
* internal runtime and end the reset request
*/
}
/* The following section of the program is broken down into several "steps" that
* represent either a turn, forward movement, or a shot from the particle accelerator by
* the robot. A variable called target is assigned a value either representing linear
* distance or angular rotation at the start of each step. The robot is then assigned an
* action to perform based on the value variable "target" is assigned to. Occasionally,
* telemetry info is also passed back to the robot controller.
*/
if (currentStep == 1) {
target = 1800;
//target = 2800;
particleLift.setPower(1.0);
driveStraight(target);
telemetry.addData("Motor1", leftMotor.getCurrentPosition());
telemetry.addData("Motor2", rightMotor.getCurrentPosition());
telemetry.addData("current positon", currentStep);
telemetry.addData("error", error);
telemetry.addData("left Power", leftMotor.getPower());
telemetry.addData("right Power", rightMotor.getPower());
telemetry.addData("Current Z:", heading);
} else if(currentStep == 2){
leftMotor.setPower(0.0);
rightMotor.setPower(0.0);
shoot();
telemetry.addData("Runtime", runTime);
} else if(currentStep == 3) {
target = 4000;
particleLift.setPower(0.0);
driveStraight(target);
telemetry.addData("Error", "Finished Early");
telemetry.addData("lMotor", leftMotor.getCurrentPosition());
telemetry.addData("rMotor", rightMotor.getCurrentPosition());
telemetry.addData("lTarget", lTarget);
telemetry.addData("rTarget", rTarget);
}else if(currentStep == 4){
gyroTarget = 90;
turn(gyroTarget);
} else if (currentStep == 5) {
target = 7000;
driveStraight(target);
telemetry.addData("lMotor", leftMotor.getCurrentPosition());
telemetry.addData("rMotor", rightMotor.getCurrentPosition());
telemetry.addData("lTarget", lTarget);
telemetry.addData("rTarget", rTarget);
/*
} else if (currentStep == 6) {
gyroTarget = -90;
reset();
telemetry.addData("lMotor", leftMotor.getCurrentPosition());
telemetry.addData("rMotor", rightMotor.getCurrentPosition());
telemetry.addData("lTarget", lTarget);
telemetry.addData("rTarget", rTarget);
turn(gyroTarget);
} else if (currentStep == 7) {
reset();
leftMotor.setPower(0.0);
rightMotor.setPower(0.0);
detectColor();
telemetry.addData("red", red);
telemetry.addData("blue", blue);
telemetry.update();
} else if (currentStep == 8) {
target = 4000;
reset();
driveStraight(target);
} else if( currentStep == 9){
reset();
leftMotor.setPower(0.0);
rightMotor.setPower(0.0);
detectColor();
telemetry.addData("red", red);
telemetry.addData("blue", blue);
telemetry.update();
} else if(currentStep == 10){
gyroTarget = -114;
reset();
turn(gyroTarget);
} else if(currentStep == 11){
target = 8000;
reset();
driveStraight(target);
*/ } else{
leftMotor.setPower(0.0);
rightMotor.setPower(0.0);
}
}
}
/**
* Drives the robot forward given a set number of encoder counts. Driving in reverse is not
* currently supported, so it is recommended to make the robot turn 180 degrees first and then
* drive forward. In addition, due to a disconnect of the right motor's encoder wire, only the
* left motor is used to gauge distance. When the target is achieved, the drive motors reset.
*
* @param target The linear distance to move in encoder counts
*/
//TODO Implement proportional control to ensure the robot drives in a straight line
private void driveStraight(int target){
leftMotor.setPower(0.6);
rightMotor.setPower(0.6);
//Drive both motors forward a little over half power
if(leftMotor.getCurrentPosition() >= target){
// && rightMotor.getCurrentPosition()>= target) {
currentStep++;
leftMotor.setPower(0.0);
rightMotor.setPower(0.0);
resetRequested = true;
/*When the target is reached, increment the current step by one, stop both drive motors,
* and request a reset.
*/
}
}
/**
* Turns the robot clockwise or counter-clockwise given a target angle. Clockwise turns are
* represented by positive gyroTarget values while counter-clockwise turns are represented by
* negative gyroTarget values. The method checks for accuracy to the target within three degrees
* to keep the method precise as possible without overshooting the target repeatedly. A very
* rough form of proportional control that needs to be revised is used to control turning speed.
*
* @param gyroTarget The target degree for the robot to turn to.
*/
//TODO Improve proportional control for turning, use variable "heading" instead of a method call
private void turn(int gyroTarget){
double lPower = Range.clip(2 * ((gyro.getIntegratedZValue() - 1) - gyroTarget), -0.2, 0.2);
double rPower = - Range.clip(2* ((gyro.getIntegratedZValue() - 1) - gyroTarget), -0.2, 0.2);
/* The rough form of proportional control mentioned earlier. A better function for
* calculating motor power should be found.
*/
leftMotor.setPower(lPower);
rightMotor.setPower(rPower);
//Set left and right motor powers as calculated before
telemetry.addData("lPower", lPower);
telemetry.addData("rPower", rPower);
telemetry.addData("Integrated Z", gyro.getIntegratedZValue()- 1);
telemetry.addData("gyroTarget", gyroTarget);
//Send data to the robot controller
if(estimateEquals(gyro.getIntegratedZValue() - 1, gyroTarget, 3)){
leftMotor.setPower(0.0);
rightMotor.setPower(0.0);
currentStep++;
resetRequested = true;
/* If the gyro heading is within three degrees of the target, stop both drive motors,
* increment the current step by one, and request a reset.
*/
}
}
/**
* Turns the robot according to distance left and right to move both motors. This has much more
* inaccuracy than turn(int gyroTurn) and is harder to use as well. The method is kept in for
* legacy reasons, but should not be used if possible. Being unfinalized code, it is
* disorganized and difficult to read at points.
*
* @param lTarget The distance in encoder counts to move the left motor
* @param rTarget The distance in encoder counts to move the right motor
*/
@Deprecated
private void turn(int lTarget, int rTarget){
boolean lAchieved = false;
boolean rAchieved = false;
//Declare booleans stating if the left or right sides have reached their target.
double lPower = Range.clip(-0.05 * ((leftMotor.getCurrentPosition() - lTarget)),
-0.8, 0.8);
//Calculate the left power via a rough method of proportional control.
double rPower = Range.clip(-0.05 * ((rightMotor.getCurrentPosition() - rTarget)),
-0.8, 0.8);
//Calculate the right power via a rough method of proportional control.
telemetry.addData("lPower", lPower);
telemetry.addData("rPower", rPower);
//Send data to the robot controller.
if(!estimateEquals(leftMotor.getCurrentPosition(), lTarget, 100)){
leftMotor.setPower(lPower);
/*If the left motor is not within 100 encoder counts of the target, run it at the power
* calculated earlier
*/
} else{
leftMotor.setPower(0.0);
lAchieved = true;
/*If the left motor is within 100 encoder counts of the target, stop it and declare
* that the left side has reached its target.
*/
}
if(!estimateEquals(rightMotor.getCurrentPosition(), rTarget, 100)){
rightMotor.setPower(rPower);
/*If the right motor is not within 100 encoder counts of the target, run it at the power
* calculated earlier
*/
} else{
rightMotor.setPower(0.0);
rAchieved = true;
/*If the right motor is within 100 encoder counts of the target, stop it and declare
* that the left side has reached its target.
*/
}
if(lAchieved && rAchieved){
currentStep++;
resetRequested = true;
/* If both motors have reached their target, increment the current step by one and
* request a reset.
*/
}
}
/**
* This method uses the data from the color sensor to tell what what color emitted light is.
* Two units of either red or blue need to be detected by the color sensor to be accurately read
* as red or blue. This condition will be checked for two seconds before the method stops
* attempting and goes to the next step. Due to the beacons being very dim, the robot needs to
* be lined up very precisely near the color beacon for this to be effective.
*/
//TODO have the push rod push out if the correct color is found
private void detectColor(){
red = colorSensor.red();
blue = colorSensor.blue();
green = colorSensor.green();
//Declare variables to hold the red, blue, and green values found by the color sensor
telemetry.addData("Blue value", blue);
telemetry.addData("Red value", red);
telemetry.addData("Green value", green);
telemetry.addData("Current step", currentStep);
//Send data to the robot controller
if(runTime.time() < 2000){
//If the runtime for this step is under two seconds, continue trying to find the color
if(blue >= 2){
telemetry.addData("Blue Achieved", true);
currentStep++;
resetRequested = true;
/* If color sensor finds a blue beacon, send data to the robot controller stating it
* has found something blue and go to the next step in the program and request reset
*/
} else if(red >= 2){
telemetry.addData("Red Achieved", true);
currentStep++;
resetRequested = true;
/* If color sensor finds a red beacon, send data to the robot controller stating it
* has found something red and go to the next step in the program and request reset
*/
}
} else{
currentStep++;
resetRequested = true;
/*Once the two seconds have elapsed and no color has been found, go to the next step and
*request a reset.
*/
}
}
/**
* Fires the cannon for seven seconds and moves onto the next step when finished.
*/
private void shoot(){
if(runTime.time() < 3500) {
particleAccelerator.setPower(1.0);
particleLift.setPower(1.0);
cannonSeal.setPosition(false ? 0.0:0.5);
} else {
particleAccelerator.setPower(0.0);
particleLift.setPower(0.0);
currentStep++;
resetRequested = true;
}
}
/**
* Resets the drive motor encoders, the Z (vertical) axis value of the gyro, and the internal
* runtime.
*/
private void reset(){
leftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
rightMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
leftMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
gyro.resetZAxisIntegrator();
runTime.reset();
}
/**
* Calculates the rotational error of the robot relative to the target angle. Was used in early
* versions of of proportional control, but the method is accurate and can be re-implemented
*
* @param targetAngle The target angle that is trying to be reached
* @return The error of the robot's rotation relative to the target
*/
private double getError(int targetAngle) {
double robotError = 0.0;
//Declare a variable to hold the calculated error
int currentHeading = gyro.getHeading();
currentHeading--;
//Get the heading from the gyro (See notes on "heading" variable)
robotError = targetAngle - gyro.getHeading();
return robotError;
//Calculate and return the rotational error of the robot
}
/**
* Checks if two values are approximately equal to each other.
*
* @param value1 The 1st value to test
* @param value2 The 2nd value
* @param threshold How far off the two values can be to be considered approximately equal
* @return A boolean statement describing if the values are equal within the threshold
*/
private boolean estimateEquals(int value1, int value2, int threshold){
if((value1 >= value2 - threshold) && (value1 <= value2 + threshold)){
return true;
} else{
return false;
}
}
}
| 38.181356 | 100 | 0.616194 |
8ef447e28d9cab407a62ccfb6a10fcff10298845 | 921 | package de.bitnoise.sonferenz.web.pages.proposal;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import com.visural.wicket.aturl.At;
import de.bitnoise.sonferenz.facade.UiFacade;
import de.bitnoise.sonferenz.model.ProposalModel;
import de.bitnoise.sonferenz.web.pages.KonferenzPage;
import de.bitnoise.sonferenz.web.pages.proposal.action.EditOrViewProposal;
@At(url = "/proposal")
public class ViewProposalPage extends KonferenzPage
{
public static final String PARAM_ID = "id";
@SpringBean
private UiFacade facade;
public ViewProposalPage(PageParameters parameters)
{
super();
int id = parameters.get(PARAM_ID).toInt();
ProposalModel talk = facade.getProposalById(id);
Model model = new Model(talk);
setResponsePage(new EditOrViewProposal().doAction(model));
}
}
| 29.709677 | 74 | 0.781759 |
c3a3f91821f74ba5cb05b9fd15b9fea200df6a6b | 860 | /* Gemma: An RPG
Copyright (C) 2013-2014 Eric Ahnell
Any questions should be directed to the author via email at: [email protected]
*/
package com.puttysoftware.gemma.support.map.generic;
public interface TypeConstants {
public static final int TYPE_GROUND = 0;
public static final int TYPE_FIELD = 1;
public static final int TYPE_CHARACTER = 2;
public static final int TYPE_PASS_THROUGH = 3;
public static final int TYPE_TELEPORT = 9;
public static final int TYPE_WALL = 10;
public static final int TYPE_BUTTON = 11;
public static final int TYPE_TOGGLE_WALL = 12;
public static final int TYPE_PLAIN_WALL = 14;
public static final int TYPE_EMPTY_SPACE = 15;
public static final int TYPE_BATTLE_CHARACTER = 16;
public static final int TYPE_SHOP = 17;
public static final int TYPES_COUNT = 21;
}
| 37.391304 | 87 | 0.740698 |
74b859c6b3c070561ef1ffe9bc0dd160a31f995c | 2,425 | package com.insightfullogic.lambdabehave.generators;
import com.insightfullogic.lambdabehave.specifications.Column;
import com.insightfullogic.lambdabehave.specifications.ThreeColumns;
import com.insightfullogic.lambdabehave.specifications.TwoColumns;
/**
* A fluent builder interface for describing how test cases get generated.
*/
public interface GeneratedDescription {
/**
* Set a new source generator.
*
* The source generator is the component which provides a source of numbers, upon which random test
* case generation is performed.
*
* If not set the default will generate random numbers.
*
* @param sourceGenerator the new source generator
* @return this
*/
GeneratedDescription withSource(SourceGenerator sourceGenerator);
/**
* Use this generator to produce a single column of example testcases.
*
* @param generator the generator to use to produce the test case values
* @param <T> the type of the values in column
* @return this
*/
<T> Column<T> example(Generator<T> generator);
/**
* Use these generators to produce two columns of example testcases.
*
* @param firstGenerator the generator to use to produce the first column of test case values
* @param secondGenerator the generator to use to produce the second column of test case values
* @param <F> the type of the values in the first column
* @param <S> the type of the values in the second column
* @return this
*/
<F, S> TwoColumns<F, S> example(
Generator<F> firstGenerator,
Generator<S> secondGenerator);
/**
* Use these generators to produce three columns of example testcases.
*
* @param firstGenerator the generator to use to produce the first column of test case values
* @param secondGenerator the generator to use to produce the second column of test case values
* @param thirdGenerator the generator to use to produce the third column of test case values
* @param <F> the type of the values in the first column
* @param <S> the type of the values in the second column
* @param <T> the type of the values in the third column
* @return this
*/
<F, S, T> ThreeColumns<F, S, T> example(
Generator<F> firstGenerator,
Generator<S> secondGenerator,
Generator<T> thirdGenerator);
}
| 37.890625 | 103 | 0.689072 |
04331daf00d26d50b9fa522183c66f494ad17efb | 161,339 | package com.sentaroh.android.SMBSync2;
/*
The MIT License (MIT)
Copyright (c) 2011 Sentaroh
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.
*/
import android.media.ExifInterface;
import android.os.Build;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.mp4.Mp4Directory;
import com.sentaroh.android.SMBSync2.SyncThread.SyncThreadWorkArea;
import com.sentaroh.android.Utilities.MiscUtil;
import com.sentaroh.android.Utilities.SafFile;
import com.sentaroh.android.Utilities.StringUtil;
import com.sentaroh.jcifs.JcifsException;
import com.sentaroh.jcifs.JcifsFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.TimeZone;
import static com.sentaroh.android.SMBSync2.Constants.APP_SPECIFIC_DIRECTORY;
import static com.sentaroh.android.SMBSync2.Constants.ARCHIVE_FILE_TYPE;
import static com.sentaroh.android.SMBSync2.Constants.SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE;
import static com.sentaroh.android.SMBSync2.Constants.SMBSYNC2_CONFIRM_REQUEST_MOVE;
import static com.sentaroh.android.SMBSync2.Constants.SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY;
import static com.sentaroh.android.SMBSync2.Constants.SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY_LONG;
import static com.sentaroh.android.SMBSync2.Constants.SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_NUMBER;
public class SyncThreadArchiveFile {
private static final Logger log= LoggerFactory.getLogger(SyncThreadArchiveFile.class);
static public int syncArchiveInternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_path, String to_path) {
File mf = new File(from_path);
int sync_result = buildArchiveListInternalToInternal(stwa, sti, from_path, from_path, mf, to_path, to_path);
return sync_result;
}
static private String getTempFilePath(SyncThreadWorkArea stwa, SyncTaskItem sti, String to_path) {
String tmp_path="";
if (to_path.startsWith("/storage/emulated/0")) tmp_path=stwa.gp.internalRootDirectory+"/"+APP_SPECIFIC_DIRECTORY+"/files/temp_file.tmp";
else {
String[] dir_parts=to_path.split("/");
if (dir_parts.length>=3) {
tmp_path="/"+dir_parts[1]+"/"+dir_parts[2]+"/"+APP_SPECIFIC_DIRECTORY+"/files/temp_file.tmp";
}
}
return tmp_path;
}
static private int moveFileInternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
File mf, File tf, String to_path, String file_name) throws IOException {
int sync_result=0;
if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) {
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
if (!sti.isSyncTestMode()) {
String dir=tf.getParent();
File lf_dir=new File(dir);
if (!lf_dir.exists()) lf_dir.mkdirs();
String tmp_path="";
if (Build.VERSION.SDK_INT<=29) {
tmp_path=stwa.gp.internalRootDirectory+"/"+APP_SPECIFIC_DIRECTORY+"/files/temp_file.tmp";
} else {
tmp_path=getTempFilePath(stwa, sti, to_path);
}
File temp_file=new File(tmp_path);
sync_result= copyFile(stwa, sti, new FileInputStream(mf),
new FileOutputStream(temp_file), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer());
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
temp_file.setLastModified(mf.lastModified());
temp_file.renameTo(tf);
}
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
tf.setLastModified(mf.lastModified());
mf.delete();
stwa.totalDeleteCount++;
SyncThread.scanMediaFile(stwa, mf.getPath());
SyncThread.scanMediaFile(stwa, tf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
}
return sync_result;
}
static private int archiveFileInternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children,
String from_path, String to_path) throws IOException {
int file_seq_no=0, sync_result=0;
ArrayList<ArchiveFileListItem>fl=buildLocalFileList(stwa, sti, children);
for(ArchiveFileListItem item:fl) {
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) {
stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path);
continue;
}
if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) {
if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name,
"", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel));
continue;
}
}
if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) {
if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result;
else return SyncTaskItem.SYNC_STATUS_ERROR;
}
file_seq_no++;
String to_file_name="", to_file_ext="", to_file_seqno="";
if (item.file_name.lastIndexOf(".")>=0) {
to_file_ext=item.file_name.substring(item.file_name.lastIndexOf("."));
to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf("."));
} else {
to_file_name=item.file_name;
}
to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no);
String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item);
if (!sti.isArchiveUseRename()) {
File tf=new File(converted_to_path+"/"+item.file_name);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileInternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileInternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), to_file_name);
}
} else {
to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name);
String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item);
File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileInternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileInternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(),
converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
}
}
}
return sync_result;
}
static private int buildArchiveListInternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_base, String from_path, File mf, String to_base, String to_path) {
stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path);
int sync_result = 0;
stwa.jcifsNtStatusCode=0;
File tf;
try {
String t_from_path = from_path.substring(from_base.length());
if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1);
if (mf.exists()) {
if (mf.isDirectory()) { // Directory copy
if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) {
if (mf.canRead()) {
// if (sti.isSyncOptionSyncEmptyDirectory()) {
// SyncThread.createDirectoryToInternalStorage(stwa, sti, to_path);
// }
File[] children = mf.listFiles();
if (children != null) {
sync_result=archiveFileInternalToInternal(stwa, sti, children, from_path, to_path);
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
for (File element : children) {
if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) {
if (!element.getName().equals(".android_secure")) {
if (!from_path.equals(to_path)) {
if (element.isDirectory()) {
if (sti.isSyncOptionSyncSubDirectory()) {
sync_result = buildArchiveListInternalToInternal(stwa, sti, from_base, from_path + "/" + element.getName(),
element, to_base, to_path + "/" + element.getName());
} else {
stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=", from_path);
}
}
} else {
stwa.util.addDebugMsg(1, "W",
String.format(stwa.context.getString(R.string.msgs_mirror_same_directory_ignored),
from_path, "/", element.getName()));
}
}
} else {
return sync_result;
}
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
}
}
} else {
stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath());
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "",
stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName()));
}
}
}
} else {
stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path);
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
} catch (IOException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
}
return sync_result;
}
static public int syncArchiveInternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_path, String to_path) {
File mf = new File(from_path);
int sync_result = buildArchiveListInternalToExternal(stwa, sti, from_path, from_path, mf, to_path, to_path);
return sync_result;
}
static private int moveFileInternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
File mf, File tf, String to_path, String file_name) throws IOException {
int result=0;
if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) {
if (Build.VERSION.SDK_INT>=24) result= moveFileInternalToExternalSetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name);
else result= moveFileInternalToExternalUnsetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name);
}
return result;
}
static private int moveFileInternalToExternalUnsetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
File mf, File tf, String to_path, String file_name) throws IOException {
int sync_result=0;
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
if (!sti.isSyncTestMode()) {
SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent());
SafFile t_df = SyncThread.createSafFile(stwa, sti, to_path, false);
if (t_df == null) {
return SyncTaskItem.SYNC_STATUS_ERROR;
}
sync_result= copyFile(stwa, sti, new FileInputStream(mf),
stwa.context.getContentResolver().openOutputStream(t_df.getUri()), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer());
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
mf.delete();
stwa.totalDeleteCount++;
SyncThread.scanMediaFile(stwa, mf.getPath());
SyncThread.scanMediaFile(stwa, tf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
return sync_result;
}
static private boolean isSdcardPath(SyncThreadWorkArea stwa,String fp) {
if (fp.startsWith(stwa.gp.safMgr.getSdcardRootPath())) return true;
else return false;
}
static private int moveFileInternalToExternalSetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
File mf, File tf, String to_path, String file_name) throws IOException {
int sync_result=0;
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
if (!sti.isSyncTestMode()) {
SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent());
String temp_path=isSdcardPath(stwa,to_path)?
stwa.gp.safMgr.getSdcardRootPath()+"/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp":
stwa.gp.safMgr.getUsbRootPath()+"/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp";
File temp_file=new File(temp_path);
OutputStream os=null;
try {
os=new FileOutputStream(temp_file);
} catch (Exception e) {
SafFile sf=SyncThread.createSafFile(stwa, sti, temp_file.getPath(), false);
os=stwa.context.getContentResolver().openOutputStream(sf.getUri());
}
SafFile to_saf=SyncThread.createSafFile(stwa, sti, tf.getPath());
if (to_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR;
to_saf.deleteIfExists();
sync_result= copyFile(stwa, sti, new FileInputStream(mf), os, from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer());
temp_file.setLastModified(mf.lastModified());
// SyncThread.deleteTempMediaStoreItem(stwa, temp_file);
SafFile from_saf = SyncThread.createSafFile(stwa, sti, temp_file.getPath());
if (from_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR;
from_saf.moveTo(to_saf);
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
mf.delete();
stwa.totalDeleteCount++;
SyncThread.scanMediaFile(stwa, mf.getPath());
SyncThread.scanMediaFile(stwa, tf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
return sync_result;
}
static private int archiveFileInternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children,
String from_path, String to_path) throws IOException {
int file_seq_no=0, sync_result=0;
ArrayList<ArchiveFileListItem>fl=buildLocalFileList(stwa, sti, children);
for(ArchiveFileListItem item:fl) {
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) {
stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path);
continue;
}
if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) {
if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name,
"", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel));
continue;
}
}
if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) {
if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result;
else return SyncTaskItem.SYNC_STATUS_ERROR;
}
file_seq_no++;
String to_file_name="", to_file_ext="", to_file_seqno="";
if (item.file_name.lastIndexOf(".")>=0) {
to_file_ext=item.file_name.substring(item.file_name.lastIndexOf("."));
to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf("."));
} else {
to_file_name=item.file_name;
}
to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no);
String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item);
if (!sti.isArchiveUseRename()) {
File tf=new File(converted_to_path+"/"+item.file_name);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileInternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileInternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), to_file_name);
}
} else {
to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name);
String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item);
File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileInternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileInternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(),
converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
}
}
}
return sync_result;
}
static private int buildArchiveListInternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_base, String from_path, File mf, String to_base, String to_path) {
stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path);
int sync_result = 0;
if (!SyncThread.isValidFileDirectoryName(stwa, sti, from_path)) {
if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result;
else return SyncTaskItem.SYNC_STATUS_ERROR;
}
stwa.jcifsNtStatusCode=0;
File tf;
try {
if (mf.exists()) {
String t_from_path = from_path.substring(from_base.length());
if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1);
if (mf.isDirectory()) { // Directory copy
if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) {
if (mf.canRead()) {
// if (sti.isSyncOptionSyncEmptyDirectory()) {
// SyncThread.createDirectoryToExternalStorage(stwa, sti, to_path);
// }
File[] children = mf.listFiles();
sync_result=archiveFileInternalToExternal(stwa, sti, children, from_path, to_path);
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
if (children != null) {
for (File element : children) {
if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) {
if (!element.getName().equals(".android_secure")) {
if (element.isDirectory()) {
if (sti.isSyncOptionSyncSubDirectory()) {
sync_result = buildArchiveListInternalToExternal(stwa, sti, from_base, from_path + "/" + element.getName(),
element, to_base, to_path + "/" + element.getName());
} else {
if (stwa.gp.settingDebugLevel >= 1)
stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path);
}
}
}
} else {
return sync_result;
}
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
}
} else {
stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "",
stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName()));
}
}
}
} else {
stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path);
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
} catch (IOException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
}
return sync_result;
}
static public int syncArchiveInternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) {
File mf = new File(from_path);
int sync_result = buildArchiveListInternalToSmb(stwa, sti, from_path, from_path, mf, to_path, to_path);
return sync_result;
}
static private int archiveFileInternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children,
String from_path, String to_path) throws IOException, JcifsException {
int file_seq_no=0, sync_result=0;
ArrayList<ArchiveFileListItem>fl=buildLocalFileList(stwa, sti, children);
for(ArchiveFileListItem item:fl) {
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) {
stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path);
continue;
}
if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) {
if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name,
"", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel));
continue;//Archive cancelled
}
}
if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) {
if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result;
else return SyncTaskItem.SYNC_STATUS_ERROR;
}
file_seq_no++;
String to_file_name="", to_file_ext="", to_file_seqno="";
if (item.file_name.lastIndexOf(".")>=0) {
to_file_ext=item.file_name.substring(item.file_name.lastIndexOf("."));
to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf("."));
} else {
to_file_name=item.file_name;
}
to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no);
String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item);
if (!sti.isArchiveUseRename()) {//Renameしない
JcifsFile jf=new JcifsFile(converted_to_path+"/"+item.file_name, stwa.targetAuth);
if (jf.exists()) {
String new_name=createArchiveSmbNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
jf=new JcifsFile(new_name, stwa.targetAuth);
sync_result= moveFileInternalToSmb(stwa, sti, item.full_path, (File)item.file, jf, jf.getPath(), to_file_name);
}
} else {
sync_result= moveFileInternalToSmb(stwa, sti, item.full_path, (File)item.file, jf, jf.getPath(), to_file_name);
}
} else {//Renameする
to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name);
String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item);
JcifsFile jf=new JcifsFile(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext, stwa.targetAuth);
if (jf.exists()) {
String new_name=createArchiveSmbNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
jf=new JcifsFile(new_name, stwa.targetAuth);
sync_result= moveFileInternalToSmb(stwa, sti, item.full_path, (File)item.file, jf, jf.getPath(), to_file_name);
}
} else {
sync_result= moveFileInternalToSmb(stwa, sti, item.full_path, (File)item.file, jf, jf.getPath(), to_file_name);
}
}
}
return sync_result;
}
static private int buildArchiveListInternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_base, String from_path, File mf, String to_base, String to_path) {
stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path);
stwa.jcifsNtStatusCode=0;
int sync_result = 0;
if (!SyncThread.isValidFileDirectoryName(stwa, sti, from_path)) {
if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result;
else return SyncTaskItem.SYNC_STATUS_ERROR;
}
JcifsFile tf;
try {
if (mf.exists()) {
String t_from_path = from_path.substring(from_base.length());
if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1);
if (mf.isDirectory()) { // Directory copy
if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) {
if (mf.canRead()) {
// if (sti.isSyncOptionSyncEmptyDirectory()) {
// SyncThread.createDirectoryToSmb(stwa, sti, to_path, stwa.targetAuth);
// }
File[] children = mf.listFiles();
if (children != null) {
sync_result=archiveFileInternalToSmb(stwa, sti, children, from_path, to_path);
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
for (File element : children) {
if (element.isDirectory()) {
if (!element.getName().equals(".android_secure")) {
while (stwa.syncTaskRetryCount > 0) {
if (sti.isSyncOptionSyncSubDirectory()) {
sync_result = buildArchiveListInternalToSmb(stwa, sti, from_base, from_path + "/" + element.getName(),
element, to_base, to_path + "/" + element.getName());
}
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
if (sync_result != SyncTaskItem.SYNC_STATUS_SUCCESS)
break;
}
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
}
}
}
} else {
stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath());
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "",
stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName()));
}
}
}
} else {
stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path);
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
} catch (IOException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
} catch (JcifsException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
}
return sync_result;
}
static private void putExceptionMsg(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path, Exception e) {
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "",
CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path);
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", e.getMessage());
String sugget_msg=SyncTaskUtil.getJcifsErrorSugestionMessage(stwa.context, MiscUtil.getStackTraceString(e));
if (!sugget_msg.equals("")) SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", sugget_msg);
if (e.getCause()!=null) SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", "", "", e.getCause().toString());
if (e instanceof JcifsException) stwa.jcifsNtStatusCode=((JcifsException)e).getNtStatus();
SyncThread.printStackTraceElement(stwa, e.getStackTrace());
stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage());
}
static private String createArchiveSmbNewFilePath(SyncThreadWorkArea stwa, SyncTaskItem sti, String path, String fn, String fe)
throws MalformedURLException, JcifsException {
String result="";
for (int i=1;i<100000;i++) {
String suffix_base=String.format("_%d", i);
JcifsFile jf=new JcifsFile(fn+suffix_base+fe, stwa.targetAuth);
if (!jf.exists()) {
result=fn+suffix_base+fe;
break;
}
}
return result;
}
static private String createArchiveLocalNewFilePath(SyncThreadWorkArea stwa, SyncTaskItem sti, String path, String fn, String fe) {
String result="";
for (int i=1;i<100000;i++) {
String suffix_base=String.format("_%d", i);
File jf=new File(fn+suffix_base+fe);
if (!jf.exists()) {
result=fn+suffix_base+fe;
break;
}
}
return result;
}
static private int moveFileInternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
File mf, JcifsFile tf, String to_path, String file_name) throws IOException, JcifsException {
int sync_result=0;
if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) {
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
if (!sti.isSyncTestMode()) {
String dir=tf.getParent();
JcifsFile jf_dir=new JcifsFile(dir,stwa.targetAuth);
if (!jf_dir.exists()) jf_dir.mkdirs();
while (stwa.syncTaskRetryCount > 0) {
sync_result= copyFile(stwa, sti, new FileInputStream(mf), tf.getOutputStream(), from_path, to_path,
tf.getName(), sti.isSyncOptionUseSmallIoBuffer());
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
try {
tf.setLastModified(mf.lastModified());
} catch(JcifsException e) {
// nop
}
mf.delete();
stwa.totalDeleteCount++;
SyncThread.scanMediaFile(stwa, mf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
}
return sync_result;
}
static public int syncArchiveExternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) {
File mf = new File(from_path);
int sync_result = buildArchiveListExternalToInternal(stwa, sti, from_path, from_path, mf, to_path, to_path);
return sync_result;
}
static private int moveFileExternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
File mf, File tf, String to_path, String file_name) throws IOException {
int sync_result=0;
if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) {
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
SafFile m_df =SyncThread.createSafFile(stwa, sti, from_path, false);
if (!sti.isSyncTestMode()) {
SyncThread.createDirectoryToInternalStorage(stwa, sti, tf.getParent());
String temp_path=isSdcardPath(stwa,to_path)?
stwa.gp.safMgr.getSdcardRootPath()+"/"+APP_SPECIFIC_DIRECTORY+"/cache/temp_file.tmp":
stwa.gp.safMgr.getUsbRootPath()+ "/"+APP_SPECIFIC_DIRECTORY+"/cache/temp_file.tmp";
File temp_file=new File(temp_path);
sync_result= copyFile(stwa, sti, stwa.context.getContentResolver().openInputStream(m_df.getUri()),
new FileOutputStream(temp_file), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer());
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
temp_file.setLastModified(mf.lastModified());
temp_file.renameTo(tf);
}
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
m_df.delete();
stwa.totalDeleteCount++;
SyncThread.scanMediaFile(stwa, from_path);
SyncThread.scanMediaFile(stwa, tf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
}
return sync_result;
}
static private int archiveFileExternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children,
String from_path, String to_path) throws IOException {
int file_seq_no=0, sync_result=0;
ArrayList<ArchiveFileListItem>fl= buildSafFileList(stwa, sti, children);
for(ArchiveFileListItem item:fl) {
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) {
stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path);
continue;
}
if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) {
if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name,
"", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel));
continue;
}
}
if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) {
if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result;
else return SyncTaskItem.SYNC_STATUS_ERROR;
}
file_seq_no++;
String to_file_name="", to_file_ext="", to_file_seqno="";
if (item.file_name.lastIndexOf(".")>=0) {
to_file_ext=item.file_name.substring(item.file_name.lastIndexOf("."));
to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf("."));
} else {
to_file_name=item.file_name;
}
to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no);
String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item);
if (!sti.isArchiveUseRename()) {
File tf=new File(converted_to_path+"/"+item.file_name);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileExternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileExternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), to_file_name);
}
} else {
to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name);
String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item);
File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileExternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileExternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(),
converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
}
}
}
return sync_result;
}
static private int buildArchiveListExternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_base, String from_path, File mf, String to_base, String to_path) {
stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path);
int sync_result = 0;
stwa.jcifsNtStatusCode=0;
File tf;
try {
if (mf.exists()) {
String t_from_path = from_path.substring(from_base.length());
if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1);
if (mf.isDirectory()) { // Directory copy
if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) {
if (mf.canRead()) {
if (sti.isSyncOptionSyncEmptyDirectory()) {
SyncThread.createDirectoryToInternalStorage(stwa, sti, to_path);
}
File[] children = mf.listFiles();
if (children != null) {
sync_result=archiveFileExternalToInternal(stwa, sti, children, from_path, to_path);
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
for (File element : children) {
if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) {
if (!element.getName().equals(".android_secure")) {
if (element.isDirectory()) {
if (sti.isSyncOptionSyncSubDirectory()) {
sync_result = buildArchiveListExternalToInternal(stwa, sti, from_base, from_path + "/" + element.getName(),
element, to_base, to_path + "/" + element.getName());
} else {
stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=", from_path);
}
}
}
} else {
return sync_result;
}
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
}
}
} else {
stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath());
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "",
stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName()));
}
}
}
} else {
stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path);
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
} catch (IOException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
}
return sync_result;
}
static public int syncArchiveExternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_path, String to_path) {
File mf = new File(from_path);
int sync_result = buildArchiveListExternalToExternal(stwa, sti, from_path, from_path, mf, to_path, to_path);
return sync_result;
}
static private int moveFileExternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
File mf, File tf, String to_path, String file_name) throws IOException {
int result=0;
if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) {
if (Build.VERSION.SDK_INT>=24) result= moveFileExternalToExternalSetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name);
else result= moveFileExternalToExternalUnsetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name);
}
return result;
}
static private int moveFileExternalToExternalUnsetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
File mf, File tf, String to_path, String file_name) throws IOException {
int sync_result=0;
if (SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
SafFile m_df =SyncThread.createSafFile(stwa, sti, from_path, false);
if (!sti.isSyncTestMode()) {
SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent());
SafFile t_df =SyncThread.createSafFile(stwa, sti, to_path, false);
if (t_df == null) {
return SyncTaskItem.SYNC_STATUS_ERROR;
}
sync_result= copyFile(stwa, sti, stwa.context.getContentResolver().openInputStream(m_df.getUri()),
stwa.context.getContentResolver().openOutputStream(t_df.getUri()), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer());
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
m_df.delete();
stwa.totalDeleteCount++;
SyncThread.scanMediaFile(stwa, from_path);
SyncThread.scanMediaFile(stwa, tf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
return sync_result;
}
static private int moveFileExternalToExternalSetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
File mf, File tf, String to_path, String file_name) throws IOException {
int sync_result=0;
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
SafFile m_df = SyncThread.createSafFile(stwa, sti, from_path);
if (!sti.isSyncTestMode()) {
SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent());
String temp_path=isSdcardPath(stwa,to_path)?
stwa.gp.safMgr.getSdcardRootPath()+"/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp":
stwa.gp.safMgr.getUsbRootPath()+ "/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp";
File temp_file=new File(temp_path);
OutputStream os=null;
try {
os=new FileOutputStream(temp_file);
} catch (Exception e) {
SafFile sf=SyncThread.createSafFile(stwa, sti, temp_file.getPath(), false);
os=stwa.context.getContentResolver().openOutputStream(sf.getUri());
}
sync_result= copyFile(stwa, sti, stwa.context.getContentResolver().openInputStream(m_df.getUri()),
os, from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer());
temp_file.setLastModified(mf.lastModified());
// SyncThread.deleteTempMediaStoreItem(stwa, temp_file);
SafFile from_saf = SyncThread.createSafFile(stwa, sti, temp_file.getPath());
if (from_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR;
SafFile to_saf = SyncThread.createSafFile(stwa, sti, tf.getPath());
if (to_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR;
from_saf.moveTo(to_saf);
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
m_df.delete();
stwa.totalDeleteCount++;
SyncThread.scanMediaFile(stwa, from_path);
SyncThread.scanMediaFile(stwa, tf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
return sync_result;
}
static private int archiveFileExternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children,
String from_path, String to_path) throws IOException {
int file_seq_no=0, sync_result=0;
ArrayList<ArchiveFileListItem>fl= buildSafFileList(stwa, sti, children);
for(ArchiveFileListItem item:fl) {
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) {
stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path);
continue;
}
if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) {
if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name,
"", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel));
continue;
}
}
if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) {
if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result;
else return SyncTaskItem.SYNC_STATUS_ERROR;
}
file_seq_no++;
String to_file_name="", to_file_ext="", to_file_seqno="";
if (item.file_name.lastIndexOf(".")>=0) {
to_file_ext=item.file_name.substring(item.file_name.lastIndexOf("."));
to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf("."));
} else {
to_file_name=item.file_name;
}
to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no);
String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item);
if (!sti.isArchiveUseRename()) {
File tf=new File(converted_to_path+"/"+item.file_name);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileExternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileExternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), to_file_name);
}
} else {
to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name);
String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item);
File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileExternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileExternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(),
converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
}
}
}
return sync_result;
}
static private int buildArchiveListExternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_base, String from_path, File mf, String to_base, String to_path) {
stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=" + to_path);
int sync_result = 0;
stwa.jcifsNtStatusCode=0;
File tf;
try {
if (mf.exists()) {
String t_from_path = from_path.substring(from_base.length());
if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1);
if (mf.isDirectory()) { // Directory copy
if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) {
if (mf.canRead()) {
// if (sti.isSyncOptionSyncEmptyDirectory()) {
// SyncThread.createDirectoryToExternalStorage(stwa, sti, to_path);
// }
File[] children = mf.listFiles();
sync_result=archiveFileExternalToExternal(stwa, sti, children, from_path, to_path);
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
if (children != null) {
for (File element : children) {
if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) {
if (!element.getName().equals(".android_secure")) {
if (!from_path.equals(to_path)) {
if (element.isDirectory()) {
if (sti.isSyncOptionSyncSubDirectory()) {
sync_result = buildArchiveListExternalToExternal(stwa, sti, from_base, from_path + "/" + element.getName(),
element, to_base, to_path + "/" + element.getName());
} else {
stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path);
}
}
} else {
stwa.util.addDebugMsg(1, "W",
String.format(stwa.context.getString(R.string.msgs_mirror_same_directory_ignored),
from_path + "/" + element.getName()));
}
}
} else {
return sync_result;
}
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
}
} else {
stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "",
stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName()));
}
}
}
} else {
stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path);
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
} catch (IOException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
}
return sync_result;
}
static public int syncArchiveExternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) {
File mf = new File(from_path);
int sync_result = buildArchiveListExternalToSmb(stwa, sti, from_path, from_path, mf, to_path, to_path);
return sync_result;
}
static private int moveFileExternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
File mf, JcifsFile tf, String to_path, String file_name) throws IOException, JcifsException {
int sync_result=0;
if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) {
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
SafFile m_df =SyncThread.createSafFile(stwa, sti, from_path, false);
if (!sti.isSyncTestMode()) {
String dir=tf.getParent();
JcifsFile jf_dir=new JcifsFile(dir,stwa.targetAuth);
if (!jf_dir.exists()) jf_dir.mkdirs();
while (stwa.syncTaskRetryCount > 0) {
sync_result= copyFile(stwa, sti, stwa.context.getContentResolver().openInputStream(m_df.getUri()),
tf.getOutputStream(), from_path, to_path,
tf.getName(), sti.isSyncOptionUseSmallIoBuffer());
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
try {
tf.setLastModified(mf.lastModified());
} catch(JcifsException e) {
// nop
}
if (!sti.isSyncTestMode()) {
stwa.totalDeleteCount++;
m_df.delete();
SyncThread.scanMediaFile(stwa, from_path);
}
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
}
return sync_result;
}
static private int archiveFileExternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children,
String from_path, String to_path) throws IOException, JcifsException {
int file_seq_no=0, sync_result=0;
ArrayList<ArchiveFileListItem>fl= buildSafFileList(stwa, sti, children);
for(ArchiveFileListItem item:fl) {
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) {
stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path);
continue;
}
if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) {
if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name,
"", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel));
continue;
}
}
if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) {
if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result;
else return SyncTaskItem.SYNC_STATUS_ERROR;
}
file_seq_no++;
String to_file_name="", to_file_ext="", to_file_seqno="";
if (item.file_name.lastIndexOf(".")>=0) {
to_file_ext=item.file_name.substring(item.file_name.lastIndexOf("."));
to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf("."));
} else {
to_file_name=item.file_name;
}
to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no);
String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item);
if (!sti.isArchiveUseRename()) {
JcifsFile tf=new JcifsFile(converted_to_path+"/"+item.file_name, stwa.targetAuth);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new JcifsFile(new_name, stwa.targetAuth);
sync_result= moveFileExternalToSmb(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileExternalToSmb(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), to_file_name);
}
} else {
to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name);
String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item);
JcifsFile tf=new JcifsFile(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext, stwa.targetAuth);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new JcifsFile(new_name, stwa.targetAuth);
sync_result= moveFileExternalToSmb(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileExternalToSmb(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(),
converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
}
}
}
return sync_result;
}
static private int buildArchiveListExternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_base, String from_path, File mf, String to_base, String to_path) {
stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path);
int sync_result = 0;
stwa.jcifsNtStatusCode=0;
JcifsFile tf;
try {
if (mf.exists()) {
String t_from_path = from_path.substring(from_base.length());
if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1);
if (mf.isDirectory()) { // Directory copy
if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) {
if (mf.canRead()) {
// if (sti.isSyncOptionSyncEmptyDirectory()) {
// SyncThread.createDirectoryToSmb(stwa, sti, to_path, stwa.targetAuth);
// }
File[] children = mf.listFiles();
if (children != null) {
sync_result=archiveFileExternalToSmb(stwa, sti, children, from_path, to_path);
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
for (File element : children) {
if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) {
if (!element.getName().equals(".android_secure")) {
while (stwa.syncTaskRetryCount > 0) {
if (element.isDirectory()) {
if (sti.isSyncOptionSyncSubDirectory()) {
sync_result = buildArchiveListExternalToSmb(stwa, sti, from_base, from_path + "/" + element.getName(),
element, to_base, to_path + "/" + element.getName());
} else {
if (stwa.gp.settingDebugLevel >= 1)
stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path);
}
}
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
if (sync_result != SyncTaskItem.SYNC_STATUS_SUCCESS)
break;
}
} else {
return sync_result;
}
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
}
}
} else {
stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath());
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "",
stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName()));
}
}
}
} else {
stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path);
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
} catch (IOException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
} catch (JcifsException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
}
return sync_result;
}
static public int syncArchiveSmbToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) {
JcifsFile mf = null;
try {
mf = new JcifsFile(from_path, stwa.masterAuth);
} catch (MalformedURLException e) {
stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path);
stwa.util.addLogMsg("E", "", e.getMessage());//e.toString());
SyncThread.printStackTraceElement(stwa, e.getStackTrace());
stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
} catch (JcifsException e) {
stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path);
stwa.util.addLogMsg("E", "", e.getMessage());//e.toString());
SyncThread.printStackTraceElement(stwa, e.getStackTrace());
stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
int sync_result = buildArchiveListSmbToInternal(stwa, sti, from_path, from_path, mf, to_path, to_path);
return sync_result;
}
static private int moveFileSmbToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
JcifsFile mf, File tf, String to_path, String file_name) throws IOException, JcifsException {
int sync_result=0;
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
if (!sti.isSyncTestMode()) {
String dir=tf.getParent();
File lf_dir=new File(dir);
if (!lf_dir.exists()) lf_dir.mkdirs();
File temp_file=new File(stwa.gp.internalRootDirectory+"/"+APP_SPECIFIC_DIRECTORY+"/cache/temp_file.tmp");
while (stwa.syncTaskRetryCount > 0) {
sync_result= copyFile(stwa, sti, mf.getInputStream(), new FileOutputStream(temp_file), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer());
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
temp_file.setLastModified(mf.getLastModified());
temp_file.renameTo(tf);
}
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
try {
tf.setLastModified(mf.getLastModified());
} catch(JcifsException e) {
// nop
}
mf.delete();
stwa.totalDeleteCount++;
SyncThread.scanMediaFile(stwa, tf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
return sync_result;
}
static private int archiveFileSmbToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile[] children,
String from_path, String to_path) throws IOException, JcifsException {
int file_seq_no=0, sync_result=0;
ArrayList<ArchiveFileListItem>fl=buildSmbFileList(stwa, sti, children);
for(ArchiveFileListItem item:fl) {
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) {
stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path);
continue;
}
if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) {
if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name,
"", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel));
continue;
}
}
file_seq_no++;
String to_file_name="", to_file_ext="", to_file_seqno="";
if (item.file_name.lastIndexOf(".")>=0) {
to_file_ext=item.file_name.substring(item.file_name.lastIndexOf("."));
to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf("."));
} else {
to_file_name=item.file_name;
}
to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no);
String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item);
if (!sti.isArchiveUseRename()) {
File tf=new File(converted_to_path+"/"+item.file_name);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileSmbToInternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileSmbToInternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), to_file_name);
}
} else {
to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name);
String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item);
File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileSmbToInternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileSmbToInternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(),
converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
}
}
}
return sync_result;
}
static private int buildArchiveListSmbToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_base, String from_path, JcifsFile mf, String to_base, String to_path) {
if (stwa.gp.settingDebugLevel >= 2)
stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName() + " entered, from=" + from_path + ", to=" + to_path);
int sync_result = 0;
stwa.jcifsNtStatusCode=0;
try {
if (mf.exists()) {
String t_from_path = from_path.substring(from_base.length());
if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1);
if (mf.isDirectory()) { // Directory copy
if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) {
if (mf.canRead()) {
// if (sti.isSyncOptionSyncEmptyDirectory()) {
// SyncThread.createDirectoryToInternalStorage(stwa, sti, to_path);
// }
JcifsFile[] children = mf.listFiles();
if (children != null) {
sync_result=archiveFileSmbToInternal(stwa, sti, children, from_path, to_path);
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
for (JcifsFile element : children) {
if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) {
while (stwa.syncTaskRetryCount > 0) {
if (element.isDirectory()) {
if (sti.isSyncOptionSyncSubDirectory()) {
sync_result = buildArchiveListSmbToInternal(stwa, sti, from_base, from_path + element.getName(),
element, to_base, to_path + "/" + element.getName().replace("/", ""));
} else {
if (stwa.gp.settingDebugLevel >= 1)
stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path);
}
}
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
if (sync_result != SyncTaskItem.SYNC_STATUS_SUCCESS) break;
} else {
return sync_result;
}
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
}
}
} else {
if (stwa.gp.settingDebugLevel >= 1)
stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath());
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "",
stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName()));
}
}
}
} else {
stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path);
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
} catch (IOException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
} catch (JcifsException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
}
return sync_result;
}
static public int syncArchiveSmbToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) {
stwa.smbFileList = new ArrayList<String>();
JcifsFile mf = null;
try {
mf = new JcifsFile(from_path, stwa.masterAuth);
} catch (MalformedURLException e) {
stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path);
stwa.util.addLogMsg("E", "", e.getMessage());//e.toString());
SyncThread.printStackTraceElement(stwa, e.getStackTrace());
stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
} catch (JcifsException e) {
stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path);
stwa.util.addLogMsg("E", "", e.getMessage());//e.toString());
SyncThread.printStackTraceElement(stwa, e.getStackTrace());
stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
int sync_result = buildArchiveListSmbToExternal(stwa, sti, from_path, from_path, mf, to_path, to_path);
return sync_result;
}
static private int moveFileSmbToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
JcifsFile mf, File tf, String to_path, String file_name) throws IOException, JcifsException {
int result=0;
if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) {
if (Build.VERSION.SDK_INT>=24) result= moveFileSmbToExternalSetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name);
else result= moveFileSmbToExternalUnsetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name);
}
return result;
}
static private int moveFileSmbToExternalUnsetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
JcifsFile mf, File tf, String to_path, String file_name) throws IOException, JcifsException {
int sync_result=0;
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
if (!sti.isSyncTestMode()) {
SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent());
SafFile t_df =SyncThread.createSafFile(stwa, sti, to_path, false);
if (t_df == null) {
return SyncTaskItem.SYNC_STATUS_ERROR;
}
while (stwa.syncTaskRetryCount > 0) {
sync_result= copyFile(stwa, sti, mf.getInputStream(), stwa.context.getContentResolver().openOutputStream(t_df.getUri()),
from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer());
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
try {
tf.setLastModified(mf.getLastModified());
} catch(JcifsException e) {
// nop
}
mf.delete();
stwa.totalDeleteCount++;
SyncThread.scanMediaFile(stwa, tf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
return sync_result;
}
static private int moveFileSmbToExternalSetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
JcifsFile mf, File tf, String to_path, String file_name) throws IOException, JcifsException {
int sync_result=0;
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
if (!sti.isSyncTestMode()) {
SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent());
OutputStream os=null;
String temp_path=isSdcardPath(stwa,to_path)?
stwa.gp.safMgr.getSdcardRootPath()+"/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp":
stwa.gp.safMgr.getUsbRootPath()+ "/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp";
File temp_file=new File(temp_path);
try {
os=new FileOutputStream(temp_file);
} catch (Exception e) {
SafFile sf=SyncThread.createSafFile(stwa, sti, temp_file.getPath(), false);
os=stwa.context.getContentResolver().openOutputStream(sf.getUri());
}
while (stwa.syncTaskRetryCount > 0) {
sync_result= copyFile(stwa, sti, mf.getInputStream(), os, from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer());
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
temp_file.setLastModified(mf.getLastModified());
// SyncThread.deleteTempMediaStoreItem(stwa, temp_file);
SafFile from_saf = SyncThread.createSafFile(stwa, sti, temp_file.getPath());
if (from_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR;
SafFile to_saf = SyncThread.createSafFile(stwa, sti, tf.getPath());
if (to_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR;
from_saf.moveTo(to_saf);
}
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
try {
tf.setLastModified(mf.getLastModified());
} catch(JcifsException e) {
// nop
}
mf.delete();
stwa.totalDeleteCount++;
SyncThread.scanMediaFile(stwa, tf.getPath());
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
return sync_result;
}
static private int archiveFileSmbToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile[] children,
String from_path, String to_path) throws IOException, JcifsException {
int file_seq_no=0, sync_result=0;
ArrayList<ArchiveFileListItem>fl=buildSmbFileList(stwa, sti, children);
for(ArchiveFileListItem item:fl) {
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) {
stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path);
continue;
}
if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) {
if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name,
"", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel));
continue;
}
}
file_seq_no++;
String to_file_name="", to_file_ext="", to_file_seqno="";
if (item.file_name.lastIndexOf(".")>=0) {
to_file_ext=item.file_name.substring(item.file_name.lastIndexOf("."));
to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf("."));
} else {
to_file_name=item.file_name;
}
to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no);
String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item);
if (!sti.isArchiveUseRename()) {
File tf=new File(converted_to_path+"/"+item.file_name);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileSmbToExternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileSmbToExternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), to_file_name);
}
} else {
to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name);
String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item);
File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
if (tf.exists()) {
String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new File(new_name);
sync_result= moveFileSmbToExternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileSmbToExternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(),
converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
}
}
}
return sync_result;
}
static private int buildArchiveListSmbToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_base, String from_path, JcifsFile mf, String to_base, String to_path) {
stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path + ", to=", to_path);
int sync_result = 0;
stwa.jcifsNtStatusCode=0;
File tf;
try {
if (mf.exists()) {
String t_from_path = from_path.substring(from_base.length());
if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1);
if (mf.isDirectory()) { // Directory copy
if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) {
if (mf.canRead()) {
// if (sti.isSyncOptionSyncEmptyDirectory()) {
// SyncThread.createDirectoryToExternalStorage(stwa, sti, to_path);
// }
JcifsFile[] children = mf.listFiles();
if (children != null) {
sync_result=archiveFileSmbToExternal(stwa, sti, children, from_path, to_path);
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
for (JcifsFile element : children) {
if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) {
while (stwa.syncTaskRetryCount > 0) {
if (element.isDirectory()) {
if (sti.isSyncOptionSyncSubDirectory()) {
sync_result = buildArchiveListSmbToExternal(stwa, sti, from_base, from_path + element.getName(),
element, to_base, to_path + "/" + element.getName().replace("/", ""));
} else {
if (stwa.gp.settingDebugLevel >= 1)
stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path);
}
}
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
if (sync_result != SyncTaskItem.SYNC_STATUS_SUCCESS) break;
} else {
return sync_result;
}
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
}
}
} else {
stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath());
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "",
stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName()));
}
}
}
} else {
stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path);
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
} catch (IOException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
} catch (JcifsException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
}
return sync_result;
}
static public int syncArchiveSmbToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_path, String to_path) {
JcifsFile mf = null;
try {
mf = new JcifsFile(from_path, stwa.masterAuth);
} catch (MalformedURLException e) {
stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", Master file error");
stwa.util.addLogMsg("E", "", e.getMessage());//e.toString());
SyncThread.printStackTraceElement(stwa, e.getStackTrace());
stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
} catch (JcifsException e) {
stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path);
stwa.util.addLogMsg("E", "", e.getMessage());//e.toString());
SyncThread.printStackTraceElement(stwa, e.getStackTrace());
stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
int sync_result = buildArchiveListSmbToSmb(stwa, sti, from_path, from_path, mf, to_path, to_path);
return sync_result;
}
static private int moveFileSmbToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path,
JcifsFile mf, JcifsFile tf, String to_path, String file_name) throws IOException, JcifsException {
int sync_result=0;
if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) {
if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) {
if (!sti.isSyncTestMode()) {
String dir=tf.getParent();
JcifsFile jf_dir=new JcifsFile(dir,stwa.targetAuth);
if (!jf_dir.exists()) jf_dir.mkdirs();
while (stwa.syncTaskRetryCount > 0) {
sync_result= copyFile(stwa, sti, mf.getInputStream(), tf.getOutputStream(), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer());
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
}
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
stwa.totalCopyCount++;
SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(),
"", stwa.msgs_mirror_task_file_archived);
if (!sti.isSyncTestMode()) {
try {
tf.setLastModified(mf.getLastModified());
} catch(JcifsException e) {
// nop
}
mf.delete();
stwa.totalDeleteCount++;
}
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(),
"", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel));
}
}
return sync_result;
}
static private int archiveFileSmbToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile[] children,
String from_path, String to_path) throws IOException, JcifsException {
int file_seq_no=0, sync_result=0;
ArrayList<ArchiveFileListItem>fl=buildSmbFileList(stwa, sti, children);
for(ArchiveFileListItem item:fl) {
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) {
stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path);
continue;
}
if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) {
if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name,
"", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel));
continue;
}
}
file_seq_no++;
String to_file_name="", to_file_ext="", to_file_seqno="";
if (item.file_name.lastIndexOf(".")>=0) {
to_file_ext=item.file_name.substring(item.file_name.lastIndexOf("."));
to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf("."));
} else {
to_file_name=item.file_name;
}
to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no);
String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item);
if (!sti.isArchiveUseRename()) {
JcifsFile tf=new JcifsFile(converted_to_path+"/"+item.file_name, stwa.targetAuth);
if (tf.exists()) {
String new_name=createArchiveSmbNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new JcifsFile(new_name, stwa.targetAuth);
sync_result= moveFileSmbToSmb(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileSmbToSmb(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), to_file_name);
}
} else {
to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name);
String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item);
JcifsFile tf=new JcifsFile(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext, stwa.targetAuth);
if (tf.exists()) {
String new_name=createArchiveSmbNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ;
if (new_name.equals("")) {
stwa.util.addLogMsg("E","Archive sequence number overflow error.");
sync_result=SyncTaskItem.SYNC_STATUS_ERROR;
break;
} else {
tf=new JcifsFile(new_name, stwa.targetAuth);
sync_result= moveFileSmbToSmb(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name);
}
} else {
sync_result= moveFileSmbToSmb(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(),
converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext);
}
}
}
return sync_result;
}
static private int buildArchiveListSmbToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti,
String from_base, String from_path, JcifsFile mf, String to_base, String to_path) {
stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path);
int sync_result = 0;
stwa.jcifsNtStatusCode=0;
JcifsFile tf;
try {
if (mf.exists()) {
String t_from_path = from_path.substring(from_base.length());
if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1);
if (mf.isDirectory()) { // Directory copy
if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) {
if (mf.canRead()){
// if (sti.isSyncOptionSyncEmptyDirectory()) {
// SyncThread.createDirectoryToSmb(stwa, sti, to_path, stwa.targetAuth);
// }
JcifsFile[] children = mf.listFiles();
if (children != null) {
sync_result=archiveFileSmbToSmb(stwa, sti, children, from_path, to_path);
if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) {
for (JcifsFile element : children) {
if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) {
while (stwa.syncTaskRetryCount > 0) {
if (element.isDirectory()) {
if (sti.isSyncOptionSyncSubDirectory()) {
sync_result = buildArchiveListSmbToSmb(stwa, sti, from_base, from_path + element.getName(),
element, to_base, to_path + element.getName());
} else {
if (stwa.gp.settingDebugLevel >= 1)
stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path);
}
}
if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) {
stwa.syncTaskRetryCount--;
if (stwa.syncTaskRetryCount > 0)
sync_result = waitRetryInterval(stwa);
if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL)
break;
} else {
stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal;
break;
}
}
if (sync_result != SyncTaskItem.SYNC_STATUS_SUCCESS) break;
} else {
return sync_result;
}
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
sync_result = SyncTaskItem.SYNC_STATUS_CANCEL;
break;
}
}
}
} else {
if (stwa.gp.settingDebugLevel >= 1)
stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath());
}
} else {
stwa.totalIgnoreCount++;
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "",
stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName()));
}
}
}
} else {
stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path);
SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage());
return SyncTaskItem.SYNC_STATUS_ERROR;
}
} catch (IOException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
} catch (JcifsException e) {
putExceptionMsg(stwa, sti, from_path, to_path, e);
return SyncTaskItem.SYNC_STATUS_ERROR;
}
return sync_result;
}
static private int waitRetryInterval(SyncThreadWorkArea stwa) {
int result = 0;
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
result = SyncTaskItem.SYNC_STATUS_CANCEL;
} else {
synchronized (stwa.gp.syncThreadCtrl) {
try {
stwa.gp.syncThreadCtrl.wait(1000 * SyncThread.SYNC_RETRY_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (!stwa.gp.syncThreadCtrl.isEnabled())
result = SyncTaskItem.SYNC_STATUS_CANCEL;
}
return result;
}
final static int SHOW_PROGRESS_THRESHOLD_VALUE=512;
static private int copyFile(SyncThreadWorkArea stwa, SyncTaskItem sti, InputStream ifs, OutputStream ofs, String from_path,
String to_path, String file_name, boolean small_buffer) throws IOException {
stwa.util.addDebugMsg(2, "I", "copyFile from=", from_path, ", to=", to_path);
int buff_size=0, io_area_size=0;
if (small_buffer) {
buff_size=1024*16-1;
io_area_size=buff_size;
} else {
buff_size=1024*1024*4;
io_area_size=1024*1024*2;
}
long read_begin_time = System.currentTimeMillis();
if (sti.isSyncTestMode()) return SyncTaskItem.SYNC_STATUS_SUCCESS;
int buffer_read_bytes = 0;
long file_read_bytes = 0;
long file_size = ifs.available();
boolean show_prog = (file_size > SHOW_PROGRESS_THRESHOLD_VALUE);
byte[] buffer = new byte[io_area_size];
while ((buffer_read_bytes = ifs.read(buffer)) > 0) {
ofs.write(buffer, 0, buffer_read_bytes);
file_read_bytes += buffer_read_bytes;
if (show_prog && file_size > file_read_bytes) {
SyncThread.showProgressMsg(stwa, sti.getSyncTaskName(), file_name + " " +
String.format(stwa.msgs_mirror_task_file_copying, (file_read_bytes * 100) / file_size));
}
if (!stwa.gp.syncThreadCtrl.isEnabled()) {
ifs.close();
ofs.flush();
ofs.close();
return SyncTaskItem.SYNC_STATUS_CANCEL;
}
}
ifs.close();
ofs.flush();
ofs.close();
long file_read_time = System.currentTimeMillis() - read_begin_time;
if (stwa.gp.settingDebugLevel >= 1)
stwa.util.addDebugMsg(1, "I", to_path + " " + file_read_bytes + " bytes transfered in ",
file_read_time + " mili seconds at " +
SyncThread.calTransferRate(file_read_bytes, file_read_time));
stwa.totalTransferByte += file_read_bytes;
stwa.totalTransferTime += file_read_time;
return SyncTaskItem.SYNC_STATUS_SUCCESS;
}
static private class ArchiveFileListItem {
Object file=null;
String shoot_date="", shoot_time="";
String shoot_week_number="", shoot_week_day="", shoot_week_day_long="";
String file_name="";
String full_path="";
long file_size=0L;
boolean date_from_exif=true;
}
static private ArrayList<ArchiveFileListItem> buildLocalFileList(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children) {
ArrayList<ArchiveFileListItem>fl=new ArrayList<ArchiveFileListItem>();
for(File element:children) {
if (element.isFile() && isFileTypeArchiveTarget(element.getName())) {
String[] date_time=getFileExifDateTime(stwa, sti, element);
ArchiveFileListItem afli=new ArchiveFileListItem();
afli.file=element;
afli.file_name=element.getName();
afli.full_path=element.getPath();
afli.file_size=element.length();
Date date=null;
if (date_time==null || date_time[0]==null) {
String[] dt= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(element.lastModified()).split(" ");
afli.shoot_date=dt[0].replace("/","-");
afli.shoot_time=dt[1].replace(":","-");
date=new Date(element.lastModified());
afli.date_from_exif=false;
} else {
// Log.v("SMBSync2","name="+afli.file_name+", 0="+date_time[0]+", 1="+date_time[1]);
date=new Date(date_time[0]+" "+date_time[1]);
String[] dt= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(date.getTime()).split(" ");
afli.shoot_date=date_time[0].replace("/","-");
afli.shoot_time=date_time[1].replace(":","-");
}
SimpleDateFormat sdf=new SimpleDateFormat(("w"));
afli.shoot_week_number=sdf.format(date.getTime());
afli.shoot_week_day=getWeekDay(date.getTime());
afli.shoot_week_day_long=getWeekDay(date.getTime());
if (isFileArchiveRequired(stwa, sti, afli)) fl.add(afli);
}
}
Collections.sort(fl, new Comparator<ArchiveFileListItem>(){
@Override
public int compare(ArchiveFileListItem ri, ArchiveFileListItem li) {
return (ri.shoot_date+ri.shoot_time+ri.file_name).compareToIgnoreCase(li.shoot_date+li.shoot_time+li.file_name);
}
});
return fl;
}
static private ArrayList<ArchiveFileListItem> buildSafFileList(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children) {
ArrayList<ArchiveFileListItem>fl=new ArrayList<ArchiveFileListItem>();
for(File element:children) {
if (element.isFile() && isFileTypeArchiveTarget(element.getName())) {
SafFile m_df = SyncThread.createSafFile(stwa, sti, element.getPath(), false);
String[] date_time=getFileExifDateTime(stwa, sti, m_df);
ArchiveFileListItem afli=new ArchiveFileListItem();
afli.file=element;
afli.file_name=element.getName();
afli.full_path=element.getPath();
afli.file_size=element.length();
Date date=null;
if (date_time==null || date_time[0]==null) {
String[] dt= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(element.lastModified()).split(" ");
date=new Date(dt[0]+" "+dt[1]);
afli.shoot_date=dt[0].replace("/","-");
afli.shoot_time=dt[1].replace(":","-");
afli.date_from_exif=false;
} else {
date=new Date(date_time[0]+" "+date_time[1]);
afli.shoot_date=date_time[0].replace("/","-");
afli.shoot_time=date_time[1].replace(":","-");
}
SimpleDateFormat sdf=new SimpleDateFormat(("w"));
afli.shoot_week_number=sdf.format(date.getTime());
afli.shoot_week_day=getWeekDay(date.getTime());
afli.shoot_week_day_long=getWeekDay(date.getTime());
if (isFileArchiveRequired(stwa, sti, afli)) fl.add(afli);
}
}
Collections.sort(fl, new Comparator<ArchiveFileListItem>(){
@Override
public int compare(ArchiveFileListItem ri, ArchiveFileListItem li) {
return (ri.shoot_date+ri.shoot_time+ri.file_name).compareToIgnoreCase(li.shoot_date+li.shoot_time+li.file_name);
}
});
return fl;
}
static final private boolean isFileTypeArchiveTarget(String name) {
boolean result=false;
for(String item:ARCHIVE_FILE_TYPE) {
if (name.toLowerCase().endsWith("."+item)) {
result=true;
break;
}
}
return result;
}
static private ArrayList<ArchiveFileListItem> buildSmbFileList(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile[] children) throws JcifsException {
ArrayList<ArchiveFileListItem>fl=new ArrayList<ArchiveFileListItem>();
for(JcifsFile element:children) {
if (element.isFile() && isFileTypeArchiveTarget(element.getName())) {
String[] date_time=getFileExifDateTime(stwa, sti, element);
ArchiveFileListItem afli=new ArchiveFileListItem();
afli.file=element;
afli.file_name=element.getName();
afli.full_path=element.getPath();
afli.file_size=element.length();
Date date=null;
if (date_time==null || date_time[0]==null) {
String[] dt= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(element.getLastModified()).split(" ");
date=new Date(dt[0]+" "+dt[1]);
afli.shoot_date=dt[0].replace("/","-");
afli.shoot_time=dt[1].replace(":","-");
afli.date_from_exif=false;
} else {
date=new Date(date_time[0]+" "+date_time[1]);
afli.shoot_date=date_time[0].replace("/","-");
afli.shoot_time=date_time[1].replace(":","-");
}
SimpleDateFormat sdf=new SimpleDateFormat(("w"));
afli.shoot_week_number=sdf.format(date.getTime());
sdf=new SimpleDateFormat(("EEE"));
afli.shoot_week_day=getWeekDay(date.getTime());
afli.shoot_week_day_long=getWeekDay(date.getTime());
if (isFileArchiveRequired(stwa, sti, afli)) fl.add(afli);
}
}
Collections.sort(fl, new Comparator<ArchiveFileListItem>(){
@Override
public int compare(ArchiveFileListItem ri, ArchiveFileListItem li) {
return (ri.shoot_date+ri.shoot_time+ri.file_name).compareToIgnoreCase(li.shoot_date+li.shoot_time+li.file_name);
}
});
return fl;
}
static private String getWeekDay(long time) {
SimpleDateFormat sdf=new SimpleDateFormat(("w"));
sdf=new SimpleDateFormat(("EEE"));
String tmp=sdf.format(time).toLowerCase();
String result=tmp.endsWith(".")?tmp.substring(0, tmp.length()-1):tmp;
return result;
}
static private String getWeekDayLong(long time) {
SimpleDateFormat sdf=new SimpleDateFormat(("w"));
sdf=new SimpleDateFormat(("EEEE"));
String tmp=sdf.format(time).toLowerCase();
String result=tmp.endsWith(".")?tmp.substring(0, tmp.length()-1):tmp;
return result;
}
static final public boolean isFileArchiveRequired(SyncThreadWorkArea stwa, SyncTaskItem sti, ArchiveFileListItem afli) {
Calendar cal=Calendar.getInstance() ;
String[] dt=afli.shoot_date.split("-");
String[] tm=afli.shoot_time.split("-");
cal.set(Integer.parseInt(dt[0]),Integer.parseInt(dt[1])-1,Integer.parseInt(dt[2]),
Integer.parseInt(tm[0]),Integer.parseInt(tm[1]),Integer.parseInt(tm[2]));
String c_ft= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(cal.getTimeInMillis());
long exp_time=0, day_mili=1000L*60L*60L*24L;
if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_7_DAYS) exp_time=day_mili*7L;
else if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_30_DAYS) exp_time=day_mili*30L;
else if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_60_DAYS) exp_time=day_mili*60L;
else if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_90_DAYS) exp_time=day_mili*90L;
else if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_180_DAYS) exp_time=day_mili*180L;
else if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_1_YEARS) {
int n_year=cal.getTime().getYear();
Calendar n_cal=Calendar.getInstance() ;
n_cal.setTimeInMillis(cal.getTimeInMillis());
n_cal.add(Calendar.YEAR, 1);
exp_time=n_cal.getTimeInMillis()-cal.getTimeInMillis();
}
String n_exp= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(cal.getTimeInMillis()+exp_time);
// boolean result=(System.currentTimeMillis()>cal.getTimeInMillis());
boolean result=(System.currentTimeMillis()>(cal.getTimeInMillis()+exp_time));
stwa.util.addDebugMsg(1,"I","isFileArchiveRequired path=",afli.full_path,", shoot date=",afli.shoot_date,
", shoot time=", afli.shoot_time,", exif="+afli.date_from_exif,", archive required="+result, ", " +
"retention period="+sti.getArchiveRetentionPeriod(), ", expiration date=", n_exp, ", expiration period="+exp_time);
return result;
}
static private String buildArchiveSubDirectoryName(SyncThreadWorkArea stwa, SyncTaskItem sti, ArchiveFileListItem afli) {
String temp_dir="";
if (sti.isArchiveCreateDirectory()) {
if (!sti.getArchiveCreateDirectoryTemplate().equals("")){
String year=afli.shoot_date.substring(0,4);
String month=afli.shoot_date.substring(5,7);
String day=afli.shoot_date.substring(8,10);
temp_dir=sti.getArchiveCreateDirectoryTemplate().replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_YEAR,year)
.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_MONTH,month)
.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_DAY,day)
.replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_NUMBER,afli.shoot_week_number)
.replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY,afli.shoot_week_day)
.replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY_LONG,afli.shoot_week_day_long)
+"/";
}
}
return temp_dir;
}
static private String buildArchiveTargetDirectoryName(SyncThreadWorkArea stwa, SyncTaskItem sti, String to_path, ArchiveFileListItem afli) {
String target_directory="";
if (sti.isTargetUseTakenDateTimeToDirectoryNameKeyword()) {
if (!to_path.equals("")){
String year=afli.shoot_date.substring(0,4);
String month=afli.shoot_date.substring(5,7);
String day=afli.shoot_date.substring(8,10);
target_directory=to_path.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_YEAR,year)
.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_MONTH,month)
.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_DAY,day)
.replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_NUMBER,afli.shoot_week_number)
.replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY,afli.shoot_week_day)
.replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY_LONG,afli.shoot_week_day_long)
;
}
} else {
target_directory=to_path;
}
return target_directory;
}
static private String buildArchiveFileName(SyncThreadWorkArea stwa, SyncTaskItem sti, ArchiveFileListItem afli, String original_name) {
String to_file_name=original_name;
if (!sti.getArchiveRenameFileTemplate().equals("")) {
to_file_name=sti.getArchiveRenameFileTemplate()
.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_ORIGINAL_NAME, original_name)
.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_DATE, afli.shoot_date)
.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_TIME, afli.shoot_time)
.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_YYYYMMDD, afli.shoot_date.replaceAll("-",""))
.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_HHMMSS, afli.shoot_time.replaceAll("-",""))
;
}
return to_file_name;
}
static private String getFileSeqNumber(SyncThreadWorkArea stwa, SyncTaskItem sti, int seq_no) {
String seqno="";
if (sti.getArchiveSuffixOption().equals("2")) seqno=String.format("_%02d", seq_no);
else if (sti.getArchiveSuffixOption().equals("3")) seqno=String.format("_%03d", seq_no);
else if (sti.getArchiveSuffixOption().equals("4")) seqno=String.format("_%04d", seq_no);
else if (sti.getArchiveSuffixOption().equals("5")) seqno=String.format("_%05d", seq_no);
else if (sti.getArchiveSuffixOption().equals("6")) seqno=String.format("_%06d", seq_no);
return seqno;
}
static final public String[] getFileExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, File lf) {
String[] date_time=null;
try {
FileInputStream fis=new FileInputStream(lf);
FileInputStream fis_retry=new FileInputStream(lf);
date_time=getFileExifDateTime(stwa, sti, fis, fis_retry, lf.lastModified(), lf.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return date_time;
}
static final public String[] getFileExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, SafFile sf) {
String[] date_time=null;
try {
InputStream fis=stwa.context.getContentResolver().openInputStream(sf.getUri());
InputStream fis_retry=stwa.context.getContentResolver().openInputStream(sf.getUri());
date_time=getFileExifDateTime(stwa, sti, fis, fis_retry, sf.lastModified(), sf.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return date_time;
}
static final public String[] getFileExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile lf) throws JcifsException {
String[] date_time=null;
InputStream fis=lf.getInputStream();
InputStream fis_retry=lf.getInputStream();
date_time=getFileExifDateTime(stwa, sti, fis, fis_retry, lf.getLastModified(), lf.getName());
return date_time;
}
static final public String[] getFileExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, InputStream fis,
InputStream fis_retry, long last_mod, String file_name) {
String[] date_time=null;
if (file_name.endsWith(".mp4") || file_name.endsWith(".mov") ) {
date_time=getMp4ExifDateTime(stwa, fis);
} else {
try {
date_time=getExifDateTime(stwa, fis);//, buff);
fis.close();
if (date_time==null || date_time[0]==null) {
stwa.util.addDebugMsg(1,"W","Read exif date and time failed, name="+file_name);
if (Build.VERSION.SDK_INT>=24) {
ExifInterface ei = new ExifInterface(fis_retry);
String dt=ei.getAttribute(ExifInterface.TAG_DATETIME);
if (dt!=null) {
date_time=new String[2];
if (dt.endsWith("Z")) {
String[] date=dt.split("T");
date_time[0]=date[0].replaceAll(":", "/");//Date
date_time[1]=date[1].substring(0,date[1].length()-1);//Time
} else {
String[] date=dt.split(" ");
date_time[0]=date[0].replaceAll(":", "/");//Date
date_time[1]=date[1];//Time
}
} else {
stwa.util.addDebugMsg(1,"I","Read exif date and time failed by ExifInterface, name="+file_name);
}
}
}
} catch (IOException e) {
e.printStackTrace();
putExceptionMessage(stwa, e.getStackTrace(), e.getMessage());
}
}
// if (date_time==null || date_time[0]==null) {
// date_time= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(last_mod).split(" ");
// }
try {fis_retry.close();} catch(Exception e) {};
return date_time;
}
static final public String[] getMp4ExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile lf) throws JcifsException {
String[] result=null;
InputStream fis=lf.getInputStream();
result=getMp4ExifDateTime(stwa, fis);
return result;
}
static final public String[] getMp4ExifDateTime(SyncThreadWorkArea stwa, InputStream fis) {
String[] result=null;
try {
Metadata metaData;
metaData = ImageMetadataReader.readMetadata(fis);
Mp4Directory directory=null;
if (metaData!=null) {
directory=metaData.getFirstDirectoryOfType(Mp4Directory.class);
if (directory!=null) {
String date = directory.getString(Mp4Directory.TAG_CREATION_TIME);
result=parseDateValue(date);
if (result!=null && result[0].startsWith("1904")) result=null;
}
}
} catch (ImageProcessingException e) {
e.printStackTrace();
putExceptionMessage(stwa, e.getStackTrace(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
putExceptionMessage(stwa, e.getStackTrace(), e.getMessage());
}
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
putExceptionMessage(stwa, e.getStackTrace(), e.getMessage());
}
return result;
}
static private void putExceptionMessage(SyncThreadWorkArea stwa, StackTraceElement[] st, String e_msg) {
String st_msg=formatStackTrace(st);
stwa.util.addDebugMsg(1,"E",stwa.currentSTI.getSyncTaskName()," Error="+e_msg+st_msg);
}
static final private String[] parseDateValue(String date_val) {
String[] result=null;
if (date_val!=null) {
String[] dt=date_val.split(" ");
int year=Integer.parseInt(dt[5]);
int month=0;
int day=Integer.parseInt(dt[2]);
if (dt[1].equals("Jan")) month=0;
else if (dt[1].equals("Feb")) month=1;
else if (dt[1].equals("Mar")) month=2;
else if (dt[1].equals("Apr")) month=3;
else if (dt[1].equals("May")) month=4;
else if (dt[1].equals("Jun")) month=5;
else if (dt[1].equals("Jul")) month=6;
else if (dt[1].equals("Aug")) month=7;
else if (dt[1].equals("Sep")) month=8;
else if (dt[1].equals("Oct")) month=9;
else if (dt[1].equals("Nov")) month=10;
else if (dt[1].equals("Dec")) month=11;
String[] tm=dt[3].split(":");
int hours= Integer.parseInt(tm[0]);
int minutes=Integer.parseInt(tm[1]);
int seconds=Integer.parseInt(tm[2]);
Calendar cal=Calendar.getInstance() ;
TimeZone tz=TimeZone.getDefault();
tz.setID(dt[3]);
cal.setTimeZone(tz);
cal.set(year, month, day, hours, minutes, seconds);
result= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(cal.getTimeInMillis()).split(" ");
}
return result;
}
static final public String[] getMp4ExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, File lf) {
String[] result=null;
try {
InputStream fis=new FileInputStream(lf);
result=getMp4ExifDateTime(stwa, fis);
} catch (IOException e) {
e.printStackTrace();
putExceptionMessage(stwa, e.getStackTrace(), e.getMessage());
}
return result;
}
static final public String[] getMp4ExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, SafFile sf) {
String[] result=null;
InputStream fis=null;
try {
fis=stwa.context.getContentResolver().openInputStream(sf.getUri());
result=getMp4ExifDateTime(stwa, fis);
} catch (IOException e) {
e.printStackTrace();
putExceptionMessage(stwa, e.getStackTrace(), e.getMessage());
}
return result;
}
static private byte[] readExifData(BufferedInputStream bis, int read_size) throws IOException {
byte[] buff=new byte[read_size];
int rc=bis.read(buff,0,read_size);
if (rc>0) return buff;
else return null;
}
static public String[] getExifDateTime(SyncThreadWorkArea stwa, InputStream fis) {
BufferedInputStream bis=new BufferedInputStream(fis, 1024*32);
String[] result=null;
try {
byte[] buff=readExifData(bis, 2);
if (buff!=null && buff[0]==(byte)0xff && buff[1]==(byte)0xd8) { //JPEG SOI
while(buff!=null) {// find dde1 jpeg segemnt
buff=readExifData(bis, 4);
if (buff!=null) {
if (buff[0]==(byte)0xff && buff[1]==(byte)0xe1) { //APP1マーカ
int seg_size=getIntFrom2Byte(false, buff[2], buff[3]);
buff=readExifData(bis, 14);
if (buff!=null) {
boolean little_endian=false;
if (buff[6]==(byte)0x49 && buff[7]==(byte)0x49) little_endian=true;
int ifd_offset=getIntFrom4Byte(little_endian, buff[10], buff[11], buff[12], buff[13]);
byte[] ifd_buff=new byte[seg_size+ifd_offset];
System.arraycopy(buff,6,ifd_buff,0,8);
buff=readExifData(bis, seg_size);
if (buff!=null) {
System.arraycopy(buff,0,ifd_buff,8,seg_size);
result=process0thIfdTag(little_endian, ifd_buff, ifd_offset);
break;
} else {
stwa.util.addDebugMsg(1,"W","Read Exif date and time failed, because unpredical EOF reached.");
return null;
}
} else {
stwa.util.addDebugMsg(1,"W","Read Exif date and time failed, because unpredical EOF reached.");
return null;
}
} else {
int offset=((int)buff[2]&0xff)*256+((int)buff[3]&0xff)-2;
if (offset<1) {
stwa.util.addDebugMsg(1,"W","Read Exif date and time failed, because invalid offset.");
return null;
}
buff=readExifData(bis, offset);
}
} else {
stwa.util.addDebugMsg(1,"W","Read Exif date and time failed, because unpredical EOF reached.");
return null;
}
}
} else {
stwa.util.addDebugMsg(1,"W","Read exif date and time failed, because Exif header can not be found.");
}
} catch (Exception e) {
e.printStackTrace();
putExceptionMessage(stwa, e.getStackTrace(), e.getMessage());
return null;
}
return result;
}
// static private String[] getExifDateTime(SyncThreadWorkArea stwa, InputStream fis, byte[] buff) {
// String[] result=null;
// try {
// if (buff[0]==(byte)0xff && buff[1]==(byte)0xd8) {//if jpeg header
// int i=2;
// while(i<buff.length-3) {// find dde1 jpeg segemnt
// if (buff[i]==(byte)0xff && buff[i+1]==(byte)0xe1) {
// int seg_size=getIntFrom2Byte(false, buff[i+2], buff[i+3]);
// boolean little_endian=false;
// if (buff[i+10]==(byte)0x49 && buff[i+11]==(byte)0x49) little_endian=true;
// int ifd_offset=getIntFrom4Byte(little_endian, buff[i+14], buff[i+15], buff[i+16], buff[i+17]);
//
// byte[] ifd_buff= Arrays.copyOfRange(buff, i+10, seg_size+ifd_offset);
// result=process0thIfdTag(little_endian, ifd_buff, ifd_offset);
// break;
// } else {
// int offset=((int)buff[i+2]&0xff)*256+((int)buff[i+3]&0xff);
// i=offset+i+2;
// }
// }
//
// }
// } catch (Exception e) {
// e.printStackTrace();
// putExceptionMessage(stwa, e.getStackTrace(), e.getMessage());
// return null;
// }
// return result;
// }
static private String formatStackTrace(StackTraceElement[] st) {
String st_msg = "";
for (int i = 0; i < st.length; i++) {
st_msg += "\n at " + st[i].getClassName() + "." +
st[i].getMethodName() + "(" + st[i].getFileName() +
":" + st[i].getLineNumber() + ")";
}
return st_msg;
}
static private int getIntFrom2Byte(boolean little_endian, byte b1, byte b2) {
int result=0;
if (little_endian) result=((int)b2&0xff)*256+((int)b1&0xff);
else result=((int)b1&0xff)*256+((int)b2&0xff);
return result;
}
static private int getIntFrom4Byte(boolean little_endian, byte b1, byte b2, byte b3, byte b4) {
int result=0;
if (little_endian) result=((int)b4&0xff)*65536+((int)b3&0xff)*4096+((int)b2&0xff)*256+((int)b1&0xff);
else result=((int)b1&0xff)*65536+((int)b2&0xff)*4096+((int)b3&0xff)*256+((int)b4&0xff);
return result;
}
static private String[] process0thIfdTag(boolean little_endian, byte[]ifd_buff, int ifd_offset) {
int count=getIntFrom2Byte(little_endian, ifd_buff[ifd_offset+0], ifd_buff[ifd_offset+1]);
int i=0;
int ba=ifd_offset+2;
String[] result=null;
while(i<count) {
int tag_number=getIntFrom2Byte(little_endian, ifd_buff[ba+0], ifd_buff[ba+1]);
int tag_offset=getIntFrom4Byte(little_endian, ifd_buff[ba+8], ifd_buff[ba+9], ifd_buff[ba+10], ifd_buff[ba+11]);
if (tag_number==(0x8769&0xffff)) {//Exif IFD
result=processExifIfdTag(little_endian, ifd_buff, tag_offset);
break;
}
ba+=12;
i++;
}
return result;
}
static private String[] processExifIfdTag(boolean little_endian, byte[]ifd_buff, int ifd_offset) {
int count=getIntFrom2Byte(little_endian, ifd_buff[ifd_offset+0], ifd_buff[ifd_offset+1]);
int i=0;
int ba=ifd_offset+2;
String[] date_time=new String[2];
while(i<count) {
int tag_number=getIntFrom2Byte(little_endian, ifd_buff[ba+0], ifd_buff[ba+1]);
int tag_offset=getIntFrom4Byte(little_endian, ifd_buff[ba+8], ifd_buff[ba+9], ifd_buff[ba+10], ifd_buff[ba+11]);
if (tag_number==(0x9003&0xffff)) {//Date&Time TAG
String[] date = new String(ifd_buff, tag_offset, 19).split(" ");
if (date.length==2) {
date_time[0]=date[0].replaceAll(":", "/");//Date
date_time[1]=date[1];//Time
break;
}
}
ba+=12;
i++;
}
return date_time;
}
}
| 56.789511 | 174 | 0.533504 |
e32d6d15c540cb85acdb6443bc7ead5dfe294d63 | 15,461 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.test.packaging;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.Set;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import org.junit.Test;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.ejb.packaging.ClassFilter;
import org.hibernate.ejb.packaging.Entry;
import org.hibernate.ejb.packaging.ExplodedJarVisitor;
import org.hibernate.ejb.packaging.FileFilter;
import org.hibernate.ejb.packaging.FileZippedJarVisitor;
import org.hibernate.ejb.packaging.Filter;
import org.hibernate.ejb.packaging.InputStreamZippedJarVisitor;
import org.hibernate.ejb.packaging.JarProtocolVisitor;
import org.hibernate.ejb.packaging.JarVisitor;
import org.hibernate.ejb.packaging.JarVisitorFactory;
import org.hibernate.ejb.packaging.PackageFilter;
import org.hibernate.ejb.test.pack.defaultpar.ApplicationServer;
import org.hibernate.ejb.test.pack.explodedpar.Carpet;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Emmanuel Bernard
* @author Hardy Ferentschik
* @author Brett Meyer
*/
@SuppressWarnings("unchecked")
@RequiresDialect(H2Dialect.class)
public class JarVisitorTest extends PackagingTestCase {
@Test
public void testHttp() throws Exception {
URL url = JarVisitorFactory.getJarURLFromURLEntry(
new URL(
"jar:http://www.ibiblio.org/maven/hibernate/jars/hibernate-annotations-3.0beta1.jar!/META-INF/persistence.xml"
),
"/META-INF/persistence.xml"
);
try {
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
}
catch ( IOException ie ) {
//fail silently
return;
}
JarVisitor visitor = JarVisitorFactory.getVisitor( url, getFilters() );
assertEquals( 0, visitor.getMatchingEntries()[0].size() );
assertEquals( 0, visitor.getMatchingEntries()[1].size() );
assertEquals( 0, visitor.getMatchingEntries()[2].size() );
}
@Test
public void testInputStreamZippedJar() throws Exception {
File defaultPar = buildDefaultPar();
addPackageToClasspath( defaultPar );
Filter[] filters = getFilters();
JarVisitor jarVisitor = new InputStreamZippedJarVisitor( defaultPar.toURL(), filters, "" );
assertEquals( "defaultpar", jarVisitor.getUnqualifiedJarName() );
Set entries = jarVisitor.getMatchingEntries()[1];
assertEquals( 3, entries.size() );
Entry entry = new Entry( ApplicationServer.class.getName(), null );
assertTrue( entries.contains( entry ) );
entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null );
assertTrue( entries.contains( entry ) );
assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() );
assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() );
for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
}
@Test
public void testNestedJarProtocol() throws Exception {
File defaultPar = buildDefaultPar();
File nestedEar = buildNestedEar( defaultPar );
File nestedEarDir = buildNestedEarDir( defaultPar );
addPackageToClasspath( nestedEar );
String jarFileName = nestedEar.toURL().toExternalForm() + "!/defaultpar.par";
Filter[] filters = getFilters();
JarVisitor jarVisitor = new JarProtocolVisitor( new URL( jarFileName ), filters, "" );
//TODO should we fix the name here to reach defaultpar rather than nestedjar ??
//assertEquals( "defaultpar", jarVisitor.getUnqualifiedJarName() );
Set entries = jarVisitor.getMatchingEntries()[1];
assertEquals( 3, entries.size() );
Entry entry = new Entry( ApplicationServer.class.getName(), null );
assertTrue( entries.contains( entry ) );
entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null );
assertTrue( entries.contains( entry ) );
assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() );
assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() );
for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
jarFileName = nestedEarDir.toURL().toExternalForm() + "!/defaultpar.par";
//JarVisitor jarVisitor = new ZippedJarVisitor( jarFileName, true, true );
filters = getFilters();
jarVisitor = new JarProtocolVisitor( new URL( jarFileName ), filters, "" );
//TODO should we fix the name here to reach defaultpar rather than nestedjar ??
//assertEquals( "defaultpar", jarVisitor.getUnqualifiedJarName() );
entries = jarVisitor.getMatchingEntries()[1];
assertEquals( 3, entries.size() );
entry = new Entry( ApplicationServer.class.getName(), null );
assertTrue( entries.contains( entry ) );
entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null );
assertTrue( entries.contains( entry ) );
assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() );
assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() );
for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
}
@Test
public void testJarProtocol() throws Exception {
File war = buildWar();
addPackageToClasspath( war );
String jarFileName = war.toURL().toExternalForm() + "!/WEB-INF/classes";
Filter[] filters = getFilters();
JarVisitor jarVisitor = new JarProtocolVisitor( new URL( jarFileName ), filters, "" );
assertEquals( "war", jarVisitor.getUnqualifiedJarName() );
Set entries = jarVisitor.getMatchingEntries()[1];
assertEquals( 3, entries.size() );
Entry entry = new Entry( org.hibernate.ejb.test.pack.war.ApplicationServer.class.getName(), null );
assertTrue( entries.contains( entry ) );
entry = new Entry( org.hibernate.ejb.test.pack.war.Version.class.getName(), null );
assertTrue( entries.contains( entry ) );
assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() );
assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() );
for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
}
@Test
public void testZippedJar() throws Exception {
File defaultPar = buildDefaultPar();
addPackageToClasspath( defaultPar );
Filter[] filters = getFilters();
JarVisitor jarVisitor = new FileZippedJarVisitor( defaultPar.toURL(), filters, "" );
assertEquals( "defaultpar", jarVisitor.getUnqualifiedJarName() );
Set entries = jarVisitor.getMatchingEntries()[1];
assertEquals( 3, entries.size() );
Entry entry = new Entry( ApplicationServer.class.getName(), null );
assertTrue( entries.contains( entry ) );
entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null );
assertTrue( entries.contains( entry ) );
assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() );
assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() );
for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
}
@Test
public void testExplodedJar() throws Exception {
File explodedPar = buildExplodedPar();
addPackageToClasspath( explodedPar );
Filter[] filters = getFilters();
String dirPath = explodedPar.toURL().toExternalForm();
// TODO - shouldn't ExplodedJarVisitor take care of a trailing slash?
if ( dirPath.endsWith( "/" ) ) {
dirPath = dirPath.substring( 0, dirPath.length() - 1 );
}
JarVisitor jarVisitor = new ExplodedJarVisitor( dirPath, filters );
assertEquals( "explodedpar", jarVisitor.getUnqualifiedJarName() );
Set[] entries = jarVisitor.getMatchingEntries();
assertEquals( 1, entries[1].size() );
assertEquals( 1, entries[0].size() );
assertEquals( 1, entries[2].size() );
Entry entry = new Entry( Carpet.class.getName(), null );
assertTrue( entries[1].contains( entry ) );
for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
}
@Test
@TestForIssue(jiraKey = "HHH-6806")
public void testJarVisitorFactory() throws Exception{
//setting URL to accept vfs based protocol
URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
public URLStreamHandler createURLStreamHandler(String protocol) {
if("vfszip".equals(protocol) || "vfsfile".equals(protocol) )
return new URLStreamHandler() {
protected URLConnection openConnection(URL u)
throws IOException {
return null;
}
};
return null;
}
});
URL jarUrl = new URL ("file:./target/packages/defaultpar.par");
JarVisitor jarVisitor = JarVisitorFactory.getVisitor(jarUrl, getFilters(), null);
assertEquals(FileZippedJarVisitor.class.getName(), jarVisitor.getClass().getName());
jarUrl = new URL ("file:./target/packages/explodedpar");
jarVisitor = JarVisitorFactory.getVisitor(jarUrl, getFilters(), null);
assertEquals(ExplodedJarVisitor.class.getName(), jarVisitor.getClass().getName());
jarUrl = new URL ("vfszip:./target/packages/defaultpar.par");
jarVisitor = JarVisitorFactory.getVisitor(jarUrl, getFilters(), null);
assertEquals(FileZippedJarVisitor.class.getName(), jarVisitor.getClass().getName());
jarUrl = new URL ("vfsfile:./target/packages/explodedpar");
jarVisitor = JarVisitorFactory.getVisitor(jarUrl, getFilters(), null);
assertEquals(ExplodedJarVisitor.class.getName(), jarVisitor.getClass().getName());
}
@Test
@TestForIssue( jiraKey = "EJB-230" )
public void testDuplicateFilterExplodedJarExpected() throws Exception {
// File explodedPar = buildExplodedPar();
// addPackageToClasspath( explodedPar );
//
// Filter[] filters = getFilters();
// Filter[] dupeFilters = new Filter[filters.length * 2];
// int index = 0;
// for ( Filter filter : filters ) {
// dupeFilters[index++] = filter;
// }
// filters = getFilters();
// for ( Filter filter : filters ) {
// dupeFilters[index++] = filter;
// }
// String dirPath = explodedPar.toURL().toExternalForm();
// // TODO - shouldn't ExplodedJarVisitor take care of a trailing slash?
// if ( dirPath.endsWith( "/" ) ) {
// dirPath = dirPath.substring( 0, dirPath.length() - 1 );
// }
// JarVisitor jarVisitor = new ExplodedJarVisitor( dirPath, dupeFilters );
// assertEquals( "explodedpar", jarVisitor.getUnqualifiedJarName() );
// Set[] entries = jarVisitor.getMatchingEntries();
// assertEquals( 1, entries[1].size() );
// assertEquals( 1, entries[0].size() );
// assertEquals( 1, entries[2].size() );
// for ( Entry entry : ( Set<Entry> ) entries[2] ) {
// InputStream is = entry.getInputStream();
// if ( is != null ) {
// assertTrue( 0 < is.available() );
// is.close();
// }
// }
// for ( Entry entry : ( Set<Entry> ) entries[5] ) {
// InputStream is = entry.getInputStream();
// if ( is != null ) {
// assertTrue( 0 < is.available() );
// is.close();
// }
// }
//
// Entry entry = new Entry( Carpet.class.getName(), null );
// assertTrue( entries[1].contains( entry ) );
}
@Test
@TestForIssue(jiraKey = "HHH-7835")
public void testGetBytesFromInputStream() {
try {
File file = buildLargeJar();
long start = System.currentTimeMillis();
InputStream stream = new BufferedInputStream(
new FileInputStream( file ) );
int oldLength = getBytesFromInputStream( stream ).length;
stream.close();
long oldTime = System.currentTimeMillis() - start;
start = System.currentTimeMillis();
stream = new BufferedInputStream( new FileInputStream( file ) );
int newLength = JarVisitorFactory.getBytesFromInputStream(
stream ).length;
stream.close();
long newTime = System.currentTimeMillis() - start;
assertEquals( oldLength, newLength );
assertTrue( oldTime > newTime );
}
catch ( Exception e ) {
fail( e.getMessage() );
}
}
// This is the old getBytesFromInputStream from JarVisitorFactory before
// it was changed by HHH-7835. Use it as a regression test.
private byte[] getBytesFromInputStream(
InputStream inputStream) throws IOException {
int size;
byte[] entryBytes = new byte[0];
for ( ;; ) {
byte[] tmpByte = new byte[4096];
size = inputStream.read( tmpByte );
if ( size == -1 )
break;
byte[] current = new byte[entryBytes.length + size];
System.arraycopy( entryBytes, 0, current, 0, entryBytes.length );
System.arraycopy( tmpByte, 0, current, entryBytes.length, size );
entryBytes = current;
}
return entryBytes;
}
@Test
@TestForIssue(jiraKey = "HHH-7835")
public void testGetBytesFromZeroInputStream() {
try {
// Ensure that JarVisitorFactory#getBytesFromInputStream
// can handle 0 length streams gracefully.
InputStream emptyStream = new BufferedInputStream(
new FileInputStream( new File(
"src/test/resources/org/hibernate/ejb/test/packaging/empty.txt" ) ) );
int length = JarVisitorFactory.getBytesFromInputStream(
emptyStream ).length;
assertEquals( length, 0 );
emptyStream.close();
}
catch ( Exception e ) {
fail( e.getMessage() );
}
}
private Filter[] getFilters() {
return new Filter[] {
new PackageFilter( false, null ) {
public boolean accept(String javaElementName) {
return true;
}
},
new ClassFilter(
false, new Class[] {
Entity.class,
MappedSuperclass.class,
Embeddable.class
}
) {
public boolean accept(String javaElementName) {
return true;
}
},
new FileFilter( true ) {
public boolean accept(String javaElementName) {
return javaElementName.endsWith( "hbm.xml" ) || javaElementName.endsWith( "META-INF/orm.xml" );
}
}
};
}
}
| 37.987715 | 116 | 0.713602 |
258c70673adfd8a6b487ea374ac4eb8bd385a744 | 652 | package fi.riista.feature.permit.invoice.payment;
import fi.riista.feature.common.repository.BaseRepository;
import fi.riista.feature.permit.invoice.Invoice;
import fi.riista.util.jpa.JpaGroupingUtils;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public interface InvoicePaymentLineRepository extends BaseRepository<InvoicePaymentLine, Long> {
List<InvoicePaymentLine> findByInvoice(Invoice invoice);
default Map<Invoice, List<InvoicePaymentLine>> findAndGroupByInvoices(final Collection<Invoice> invoices) {
return JpaGroupingUtils.groupRelations(invoices, InvoicePaymentLine_.invoice, this);
}
}
| 34.315789 | 111 | 0.812883 |
675deae58eddb7bdceebde65f71575e4288e344f | 844 | package net.sf.robocode.ui.dialog;
import javax.swing.JSlider;
public final class DoubleJSlider extends JSlider {
private final int scale;
public DoubleJSlider(int min, int max, double scaledValue, int scale) {
super(scaleValue(min, scale), scaleValue(max, scale), limit(scaleValue(min, scale), scaleValue(scaledValue, scale), scaleValue(max, scale)));
this.scale = scale;
}
public int getScale() {
return scale;
}
public double getScaledValue() {
return 1. * super.getValue() / this.scale;
}
public void setScaledValue(double val) {
super.setValue(limit(getMinimum(), scaleValue(val, scale), getMaximum()));
}
private static int scaleValue(double val, int scale) {
return (int) (val * scale + .5);
}
private static int limit(int min, int v, int max) {
if (v < min) return min;
return Math.min(v, max);
}
}
| 24.823529 | 143 | 0.703791 |
e3050aecd9900aafe68fd3c502ef6a0cf4325850 | 1,409 | package org.somespc.webservices.rest.dto;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ComandoDTO
{
@XmlElement(name = "nome_job")
private String nomeJob;
@XmlElement(name = "grupo_job")
private String grupoJob;
@XmlElement(name = "nome_agendamento")
private String nomeAgendamento;
@XmlElement(name = "grupo_agendamento")
private String grupoAgendamento;
@XmlElement(name = "comando")
private String comando;
public String getNomeJob()
{
return nomeJob;
}
public void setNomeJob(String nomeJob)
{
this.nomeJob = nomeJob;
}
public String getGrupoJob()
{
return grupoJob;
}
public void setGrupoJob(String grupoJob)
{
this.grupoJob = grupoJob;
}
public String getNomeAgendamento()
{
return nomeAgendamento;
}
public void setNomeAgendamento(String nomeAgendamento)
{
this.nomeAgendamento = nomeAgendamento;
}
public String getGrupoAgendamento()
{
return grupoAgendamento;
}
public void setGrupoAgendamento(String grupoAgendamento)
{
this.grupoAgendamento = grupoAgendamento;
}
public String getComando()
{
return comando;
}
public void setComando(String comando)
{
this.comando = comando;
}
}
| 18.786667 | 61 | 0.648687 |
75a5f58ce8fd3a2fae2e2626210ce9db1abb82a5 | 1,410 | package com.ruoyi.system.service;
import java.util.List;
import com.ruoyi.system.domain.HrmsSalaryStandard;
/**
* 薪酬标准Service接口
*
* @author ruoyi
* @date 2022-01-03
*/
public interface IHrmsSalaryStandardService
{
/**
* 查询薪酬标准
*
* @param ID 薪酬标准主键
* @return 薪酬标准
*/
public HrmsSalaryStandard selectHrmsSalaryStandardByID(String ID);
/**
* 查询薪酬标准列表
*
* @param hrmsSalaryStandard 薪酬标准
* @return 薪酬标准集合
*/
public List<HrmsSalaryStandard> selectHrmsSalaryStandardList(HrmsSalaryStandard hrmsSalaryStandard);
/**
* 新增薪酬标准
*
* @param hrmsSalaryStandard 薪酬标准
* @return 结果
*/
public int insertHrmsSalaryStandard(HrmsSalaryStandard hrmsSalaryStandard);
/**
* 修改薪酬标准
*
* @param hrmsSalaryStandard 薪酬标准
* @return 结果
*/
public int updateHrmsSalaryStandard(HrmsSalaryStandard hrmsSalaryStandard);
/**
* 批量删除薪酬标准
*
* @param IDs 需要删除的薪酬标准主键集合
* @return 结果
*/
public int deleteHrmsSalaryStandardByIDs(String IDs);
/**
* 删除薪酬标准信息
*
* @param ID 薪酬标准主键
* @return 结果
*/
public int deleteHrmsSalaryStandardByID(String ID);
public List<HrmsSalaryStandard> querySalaryPay();
public List<HrmsSalaryStandard> querySalaryPayDetail(String param);
public List<HrmsSalaryStandard> querySalaryNameList();
}
| 20.735294 | 104 | 0.653191 |
f658dde9ee26f30732ef7b3b2627ca002e84a656 | 443 | import de.eskalon.commons.screen.ManagedScreen;
public class BlankScreen extends ManagedScreen {
@Override
protected void create() {
// do nothing
}
@Override
public void hide() {
// do nothing
}
@Override
public void render(float delta) {
// do nothing except having the screen cleared
}
@Override
public void resize(int width, int height) {
// do nothing
}
@Override
public void dispose() {
// do nothing
}
}
| 14.290323 | 48 | 0.688488 |
43c4dffadc1d6499af4c2dcf6a21f09fbb5ef791 | 4,371 | package io.leopard.web.session;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import io.leopard.json.Json;
@SuppressWarnings("deprecation")
public class SessionWrapper implements HttpSession {
// protected static final Log LOGGER = LogFactory.getLog(HttpSessionWrapper.class);
// private HttpSession session;
private String sid;
private Map<String, Object> map = null;
private int expiry;
private String FMT_CHARSET_KEY = "javax.servlet.jsp.jstl.fmt.request.charset";
// private SessionService sessionService;
public SessionWrapper(String sid, int expiry) {
if (sid == null || sid.length() == 0) {
throw new IllegalArgumentException("sessionId怎么会为空?");
}
this.sid = sid;
this.expiry = expiry;
// this.sessionService = sessionService;
}
/**
* 根据session id获取session key.
*
* @param sid
* @return
*/
protected String getSessionKey(String sid) {
// AssertUtil.assertNotEmpty(sid, "sessionId怎么会为空?");
if (sid == null || sid.length() == 0) {
throw new IllegalArgumentException("sessionId怎么会为空?");
}
return "sid:" + sid;
}
@SuppressWarnings("unchecked")
protected Map<String, Object> getMap() {
if (this.map == null) {
String key = this.getSessionKey(sid);
String json = Store.getInstance().get(key);
this.map = Json.toObject(json, Map.class);
// this.map = sessionService.getSession(sid);
if (map == null) {
map = new LinkedHashMap<String, Object>();
}
}
return this.map;
}
@Override
public String getId() {
return this.sid;
}
@Override
public void setAttribute(String key, Object value) {
if (FMT_CHARSET_KEY.equals(key)) {
return;
}
value = JsonSerializer.serialize(value);
this.getMap().put(key, value);
// sessionService.saveSession(this.sid, this.getMap(), expiry);
String json = Json.toJson(this.getMap());
Store.getInstance().set(getSessionKey(sid), json, expiry);
}
/**
* 只在内存中生效
*
* @param key
* @param value
*/
public void setCacheAttribute(String key, Object value) {
value = JsonSerializer.serialize(value);
this.getMap().put(key, value);
}
@Override
public Object getAttribute(String name) {
if (FMT_CHARSET_KEY.equals(name)) {
return "UTF-8";
}
Object value = this.getMap().get(name);
value = JsonSerializer.unserialize(value);
return value;
}
@Override
public Enumeration<String> getAttributeNames() {
return (new Enumerator(this.getMap().keySet(), true));
}
@Override
public void invalidate() {
this.getMap().clear();
// sessionService.removeSession(this.sid);
String key = this.getSessionKey(sid);
Store.getInstance().del(key);
}
@Override
public void removeAttribute(String key) {
this.getMap().remove(key);
String json = Json.toJson(this.getMap());
Store.getInstance().set(getSessionKey(sid), json, expiry);
// sessionService.saveSession(this.sid, this.getMap(), expiry);
}
@Override
public long getCreationTime() {
throw new UnsupportedOperationException("Not Impl.");
}
@Override
public long getLastAccessedTime() {
throw new UnsupportedOperationException("Not Impl.");
}
@Override
public int getMaxInactiveInterval() {
throw new UnsupportedOperationException("Not Impl.");
}
@Override
public ServletContext getServletContext() {
throw new UnsupportedOperationException("Not Impl.");
}
@Override
public HttpSessionContext getSessionContext() {
throw new UnsupportedOperationException("Not Impl.");
}
@Override
public Object getValue(String name) {
return this.getAttribute(name);
}
@Override
public String[] getValueNames() {
throw new UnsupportedOperationException("Not Impl.");
}
@Override
public boolean isNew() {
throw new UnsupportedOperationException("Not Impl.");
}
@Override
public void putValue(String name, Object value) {
this.setAttribute(name, value);
}
@Override
public void removeValue(String key) {
this.removeAttribute(key);
}
@Override
public void setMaxInactiveInterval(int arg0) {
throw new UnsupportedOperationException("Not Impl.");
}
}
| 23.755435 | 85 | 0.681995 |
d2f952472ca94401b0a14183cfd073c7521330b8 | 7,001 | package com.infi.lyrical;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Handler;
import com.infi.lyrical.helper.FileLog;
import com.infi.lyrical.helper.RetrofitHelper;
import com.infi.lyrical.helper.RetrofitInterface;
import com.infi.lyrical.models.SpeechResponse;
import com.infi.lyrical.models.StatusResponse;
import com.infi.lyrical.task.TaskStatusListener;
import com.infi.lyrical.util.AndroidUtils;
import com.infi.lyrical.task.TaskStatus;
import com.infi.lyrical.util.TempFolderMaker;
import java.io.IOException;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
/**
* Created by INFIi on 11/27/2017.
*/
public class LyricalApp extends Application {
public static volatile Handler applicationHandler;
public static volatile Context applicationContext;
private static CompositeDisposable mCompositeDisposable;
private static int TASK_CALLBACK_DELAY=15000;
private static int numTasks=0;
private static RequestBody apiKeyBody;
public static RetrofitInterface retrofitInterface;
private static String apiKey = "";//add api key here
private static String sample_url="https://www.havenondemand.com/sample-content/videos/hpnext.mp4";
@Override
public void onCreate() {
super.onCreate();
try {
applicationContext = getApplicationContext();
applicationHandler = new Handler(applicationContext.getMainLooper());
mCompositeDisposable = new CompositeDisposable();
retrofitInterface= RetrofitHelper.getInstance().create(RetrofitInterface.class);
apiKeyBody= RequestBody.create(MediaType.parse("text/plain"),apiKey);
TempFolderMaker.createFolders();
AndroidUtils.checkDisplaySize(applicationContext, null);
} catch (Exception e) {
FileLog.w("from application ", e.getMessage());
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
try{
AndroidUtils.checkDisplaySize(applicationContext,newConfig);
}catch (Exception e){
}
super.onConfigurationChanged(newConfig);
}
@Override
public void onTerminate() {
mCompositeDisposable.clear();
super.onTerminate();
}
public static RequestBody getApiKeyBody(){
if(apiKeyBody==null)apiKeyBody= RequestBody.create(MediaType.parse("text/plain"),apiKey);
return apiKeyBody;
}
private static void fetchResult(final String jobId, final String category,final TaskStatusListener statusListener){
mCompositeDisposable.add(retrofitInterface.getResult(jobId,apiKey)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
FileLog.e(throwable);
FileLog.updateStatusOf(jobId,TaskStatus.STATUS_FAILED,statusListener);
}
})
.subscribe(new Consumer<SpeechResponse>() {
@Override
public void accept(@NonNull final SpeechResponse speechResponse) throws Exception {
FileLog.write("Fetched results");
new AsyncTask<Void,Void,Void>(){
@Override
protected Void doInBackground(Void... voids) {
FileLog.createSubtitleJson(speechResponse,category,jobId,statusListener);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
}
}.execute();
}
}));
}
private static void retry(final String jobId,final String category,final TaskStatusListener statusListener){
AndroidUtils.runOnUIThread(new Runnable() {
@Override
public void run() {
trackThisTask(jobId,category,statusListener);
}
},TASK_CALLBACK_DELAY);
}
private static void resolveStatus(final String jobId,final String category, StatusResponse statusResponse,TaskStatusListener statusListener){
String status=statusResponse.getStatus();
if(status!=null){
if(status.equals(TaskStatus.STATUS_FINISHED)){
FileLog.write("Status finished");
fetchResult(jobId,category,statusListener);
}else if(status.equals(TaskStatus.STATUS_FAILED)){
try {
FileLog.updateStatusOf(jobId, TaskStatus.STATUS_FAILED,statusListener);
}catch (IOException io){
FileLog.e(io);
}
}else {
retry(jobId,category,statusListener);
FileLog.write("status is: "+status);
}
}else{
retry(jobId,category,statusListener);
FileLog.write("status is null");
}
}
public static void trackThisTask(final String jobId,final String category, final TaskStatusListener statusListener){
mCompositeDisposable.add(retrofitInterface.getStatus(jobId,apiKey)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
FileLog.e(throwable);
FileLog.updateStatusOf(jobId,TaskStatus.STATUS_FAILED,statusListener);
}
})
.subscribe(new Consumer<StatusResponse>() {
@Override
public void accept(@NonNull StatusResponse statusResponse) throws Exception {
FileLog.write("Recieved response object");
resolveStatus(jobId,category,statusResponse,statusListener);
}
}));
}
}
| 43.484472 | 145 | 0.585916 |
60a090eb7319d6fdfc63a999162c12315892293e | 1,052 | package org.lzjay.weixin.domain.event;
import javax.xml.bind.annotation.XmlElement;
import org.lzjay.weixin.domain.InMessage;
import com.fasterxml.jackson.annotation.JsonProperty;
public class EventInMessage extends InMessage{
private static final long serialVersionUID = 1L;
@XmlElement(name = "Event")
@JsonProperty("Event")
private String event;
@XmlElement(name = "EventKey")
@JsonProperty("EventKey")
private String eventKey;
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getEventKey() {
return eventKey;
}
public void setEventKey(String eventKey) {
this.eventKey = eventKey;
}
@Override
public String toString() {
return "EventInMessage [event=" + event + ", eventKey=" + eventKey + ", getToUserName()=" + getToUserName()
+ ", getFromUserName()=" + getFromUserName() + ", getCreateTime()=" + getCreateTime()
+ ", getMsgType()=" + getMsgType() + ", getMsgId()=" + getMsgId() + "]";
}
}
| 23.909091 | 110 | 0.673004 |
751448988fa70dc2847cd54db72a301942555b5b | 459 | package com.amyliascarlet.jsontest.bvt;
import com.amyliascarlet.lib.json.JSON;
import com.amyliascarlet.lib.json.JSONException;
import org.junit.Test;
import static org.junit.Assert.fail;
public class Bug89 {
@Test
public void testBug89() {
try {
String s = "{\"a\":з」∠)_,\"}";
JSON.parseObject(s);
fail("Expect JSONException");
} catch (JSONException e) {
// good
}
}
}
| 21.857143 | 48 | 0.590414 |
2c181a09d7b19e0265afde7158b133ba8e87d630 | 1,384 | package org.nwnx.nwnx2.jvm.constants;
/**
* This class contains all unique constants beginning with "SPELL_MAGIC".
* Non-distinct keys are filtered; only the LAST appearing was
* kept.
*/
public final class SpellMagic {
private SpellMagic() {}
public final static int CIRCLE_AGAINST_CHAOS = 103;
public final static int CIRCLE_AGAINST_EVIL = 104;
public final static int CIRCLE_AGAINST_GOOD = 105;
public final static int CIRCLE_AGAINST_LAW = 106;
public final static int FANG = 452;
public final static int MISSILE = 107;
public final static int VESTMENT = 546;
public final static int WEAPON = 544;
public static String nameOf(int value) {
if (value == 103) return "SpellMagic.CIRCLE_AGAINST_CHAOS";
if (value == 104) return "SpellMagic.CIRCLE_AGAINST_EVIL";
if (value == 105) return "SpellMagic.CIRCLE_AGAINST_GOOD";
if (value == 106) return "SpellMagic.CIRCLE_AGAINST_LAW";
if (value == 452) return "SpellMagic.FANG";
if (value == 107) return "SpellMagic.MISSILE";
if (value == 546) return "SpellMagic.VESTMENT";
if (value == 544) return "SpellMagic.WEAPON";
return "SpellMagic.(not found: " + value + ")";
}
public static String nameOf(float value) {
return "SpellMagic.(not found: " + value + ")";
}
public static String nameOf(String value) {
return "SpellMagic.(not found: " + value + ")";
}
}
| 34.6 | 73 | 0.699422 |
968a234430bf7175aca5af3d2d95851ae5935dad | 1,470 | package tech.blueglacier.storage;
import tech.blueglacier.codec.CodecUtil;
import org.apache.james.mime4j.storage.Storage;
import org.apache.james.mime4j.storage.StorageOutputStream;
import org.apache.james.mime4j.storage.StorageProvider;
import java.io.IOException;
import java.io.InputStream;
public abstract class AbstractStorageProvider implements StorageProvider {
/**
* Sole constructor.
*/
protected AbstractStorageProvider() {
totalBytesTransffered = 0;
}
/**
* This implementation creates a {@link StorageOutputStream} by calling
* {@link StorageProvider#createStorageOutputStream() createStorageOutputStream()}
* and copies the content of the given input stream to that output stream.
* It then calls {@link StorageOutputStream#toStorage()} on the output
* stream and returns this object.
*
* @param in
* stream containing the data to store.
* @return a {@link Storage} instance that can be used to retrieve the
* stored content.
* @throws IOException
* if an I/O error occurs.
*/
public final Storage store(InputStream in) throws IOException {
StorageOutputStream out = createStorageOutputStream();
totalBytesTransffered = CodecUtil.copy(in, out);
return out.toStorage();
}
private int totalBytesTransffered;
public int getTotalBytesTransffered() {
return totalBytesTransffered;
}
}
| 31.276596 | 86 | 0.704082 |
abb2953bcec8990214b73645cb1f41e71be1fdcf | 97 | import net.runelite.mapping.ObfuscatedName;
@ObfuscatedName("hm")
public interface class225 {
}
| 16.166667 | 43 | 0.793814 |
0835724009df49881f65abc42aec31d1cca27260 | 4,920 | package com.sunzn.rock.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
/**
* Created by sunzn on 2017/12/25.
*/
public class RockViewHelper {
private static final int DEFAULT_SQUARE_CIRCLE_GAP = 2;
private static final int DEFAULT_MIN_CIRCLE_RADIUS = 5;
private static final int DEFAULT_MAX_CIRCLE_RADIUS = 15;
private static final int DEFAULT_VER_CIRCLE_NUMBER = 12;
private static final int DEFAULT_PER_CIRCLE_UPDATE = 150;
private static final int DEFAULT_CIRCLE_FILL_COLOR = 0XFFFF0000;
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
this.update();
handler.postDelayed(this, circleUpdatePer);
}
void update() {
view.postInvalidate();
}
};
private Context context;
private RackVew view;
// RackVew 宽度
private int viewWidth;
// RackVew 高度
private int viewHeight;
// 圆的颜色
private int circleFillColor;
// 圆的最小半径
private int circleMinRadius;
// 圆的最大半径
private int circleMaxRadius;
// 圆和虚拟矩形的间距
private int circleSquareGap;
// 圆的虚拟容器宽高
private int squareSize;
// 圆的列数
private int columnNums;
// 垂直方向最多圆的数量
private int circleNumberVer;
// 界面刷新时间间隔
private int circleUpdatePer;
// RackVew 边距
private int viewMargin;
// 绘制圆的画笔
private Paint circlePaint;
private int[] points;
public RockViewHelper(RackVew view, Context context, AttributeSet attrs, int defStyleAttr) {
this.context = context;
this.view = view;
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RackVew, defStyleAttr, 0);
circleMinRadius = a.getInteger(R.styleable.RackVew_rv_min_circle_radius, DEFAULT_MIN_CIRCLE_RADIUS);
circleMaxRadius = a.getInteger(R.styleable.RackVew_rv_max_circle_radius, DEFAULT_MAX_CIRCLE_RADIUS);
circleSquareGap = a.getInteger(R.styleable.RackVew_rv_gap_circle_square, DEFAULT_SQUARE_CIRCLE_GAP);
circleNumberVer = a.getInteger(R.styleable.RackVew_rv_ver_circle_number, DEFAULT_VER_CIRCLE_NUMBER);
circleUpdatePer = a.getInteger(R.styleable.RackVew_rv_per_circle_update, DEFAULT_PER_CIRCLE_UPDATE);
circleFillColor = a.getInteger(R.styleable.RackVew_rv_circle_fill_color, DEFAULT_CIRCLE_FILL_COLOR);
a.recycle();
init();
}
private void init() {
circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
circlePaint.setDither(true);
circlePaint.setColor(circleFillColor);
circlePaint.setStyle(Paint.Style.FILL);
}
public void onSizeChanged(int w, int h) {
Log.e("RackVew", "w = " + w);
viewWidth = w;
viewHeight = h;
squareSize = (circleMaxRadius + circleSquareGap) * 2;
columnNums = viewWidth / squareSize;
viewMargin = viewWidth % squareSize;
points = new int[columnNums];
initPoints(points);
}
private void initPoints(int[] points) {
for (int i = 0; i < points.length; i++) {
points[i] = RackViewRandom.randInt(1, circleNumberVer);
}
}
public void onDraw(Canvas canvas) {
for (int c = 1; c <= columnNums; c++) {
int rows = -1;
int n = c - 1;
rows = points[n] + RackViewRandom.randDot();
if (rows > 0 && rows <= circleNumberVer) {
points[n] = rows;
}
for (int r = 1; r <= points[n]; r++) {
canvas.drawCircle(getX(c), getY(r), getD(r), circlePaint);
}
}
}
// public void onDraw(Canvas canvas) {
// for (int c = 1; c <= columnNums; c++) {
//
// int rows = 0;
// int n = c - 1;
//
// if (points[n] <= 0 || points[n] >= circleNumberVer) {
// rows = points[n] = RackViewRandom.randInt(1, circleNumberVer);
// } else {
// rows = points[n] = points[n] + 1;
// }
//
// for (int r = 1; r <= rows; r++) {
// canvas.drawCircle(getX(c), getY(r), getD(r), circlePaint);
// }
// }
// }
private int getX(int c) {
return (int) (viewMargin / 2 + (c - 0.5) * squareSize);
}
private int getY(int r) {
return (int) (viewHeight - (r - 0.5) * squareSize);
}
private int getD(int r) {
return circleMaxRadius - (circleMaxRadius - circleMinRadius) * (r - 1) / circleNumberVer;
}
public void start() {
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, circleUpdatePer);
}
public void stop() {
handler.removeCallbacks(runnable);
}
}
| 28.439306 | 108 | 0.614024 |
2fb07075a06d81653fe3f95affc01e300d645823 | 11,029 | package org.broadinstitute.ddp.route;
import static io.restassured.RestAssured.given;
import static org.broadinstitute.ddp.constants.RouteConstants.Header.DDP_CONTENT_STYLE;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.broadinstitute.ddp.constants.ErrorCodes;
import org.broadinstitute.ddp.constants.RouteConstants.API;
import org.broadinstitute.ddp.constants.RouteConstants.PathParam;
import org.broadinstitute.ddp.content.ContentStyle;
import org.broadinstitute.ddp.db.TransactionWrapper;
import org.broadinstitute.ddp.db.dao.JdbiClientUmbrellaStudy;
import org.broadinstitute.ddp.db.dao.JdbiRevision;
import org.broadinstitute.ddp.db.dao.JdbiUserStudyEnrollment;
import org.broadinstitute.ddp.db.dao.TemplateDao;
import org.broadinstitute.ddp.db.dao.UserAnnouncementDao;
import org.broadinstitute.ddp.db.dao.UserGovernanceDao;
import org.broadinstitute.ddp.db.dto.StudyDto;
import org.broadinstitute.ddp.model.activity.definition.template.Template;
import org.broadinstitute.ddp.model.governance.Governance;
import org.broadinstitute.ddp.model.user.EnrollmentStatusType;
import org.broadinstitute.ddp.model.user.UserAnnouncement;
import org.broadinstitute.ddp.util.TestDataSetupUtil;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
public class GetUserAnnouncementsRouteTest extends IntegrationTestSuite.TestCase {
private static TestDataSetupUtil.GeneratedTestData testData;
private static String token;
private static String url;
private static long revisionId;
private static Template msgTemplate;
private static String msgPlainText;
@BeforeClass
public static void setup() {
TransactionWrapper.useTxn(handle -> {
testData = TestDataSetupUtil.generateBasicUserTestData(handle);
token = testData.getTestingUser().getToken();
msgPlainText = "thank you!";
msgTemplate = Template.html("<strong>thank you!</strong>");
revisionId = handle.attach(JdbiRevision.class).insertStart(Instant.now().toEpochMilli(), testData.getUserId(), "test");
handle.attach(TemplateDao.class).insertTemplate(msgTemplate, revisionId);
assertNotNull(msgTemplate.getTemplateId());
// Start fresh with no announcements.
handle.attach(UserAnnouncementDao.class).deleteAllForUserAndStudy(testData.getUserId(), testData.getStudyId());
});
String endpoint = API.USER_STUDY_ANNOUNCEMENTS
.replace(PathParam.USER_GUID, "{userGuid}")
.replace(PathParam.STUDY_GUID, "{studyGuid}");
url = RouteTestUtil.getTestingBaseUrl() + endpoint;
}
@After
public void cleanup() {
TransactionWrapper.useTxn(handle -> handle.attach(UserAnnouncementDao.class)
.deleteAllForUserAndStudy(testData.getUserId(), testData.getStudyId()));
}
@Test
public void test_nonExistentUser_returns401() {
given().auth().oauth2(token)
.pathParam("userGuid", "non-existent-user")
.pathParam("studyGuid", testData.getStudyGuid())
.when().get(url)
.then().assertThat()
.statusCode(401);
}
@Test
public void test_nonExistentStudy_returns401() {
given().auth().oauth2(token)
.pathParam("userGuid", testData.getUserGuid())
.pathParam("studyGuid", "non-existent-study")
.when().get(url)
.then().assertThat()
.statusCode(401);
}
@Test
public void test_noAnnouncements_returnEmptyList() {
assertAnnouncementsJson(testData.getUserGuid(), testData.getStudyGuid())
.statusCode(200)
.body("$.size()", equalTo(0));
}
@Test
public void test_singleAnnouncement_deletedAfterRead() {
TransactionWrapper.useTxn(handle -> handle.attach(UserAnnouncementDao.class)
.insert(testData.getUserId(), testData.getStudyId(), msgTemplate.getTemplateId(), false));
assertAnnouncementsJson(testData.getUserGuid(), testData.getStudyGuid())
.statusCode(200)
.body("$.size()", equalTo(1))
.body("[0].permanent", equalTo(false))
.body("[0].message", equalTo(msgTemplate.getTemplateText()));
TransactionWrapper.useTxn(handle -> {
long numFound = handle.attach(UserAnnouncementDao.class)
.findAllForUserAndStudy(testData.getUserId(), testData.getStudyId())
.count();
assertEquals(0, numFound);
});
}
@Test
public void test_multipleAnnouncements_oldestOneFirst_andDeletedAfterRead() {
Template oldestTemplate = TransactionWrapper.withTxn(handle -> {
Template oldest = Template.html("<p>i am old</p>");
handle.attach(TemplateDao.class).insertTemplate(oldest, revisionId);
assertNotNull(oldest.getTemplateId());
long nowMillis = Instant.now().toEpochMilli();
UserAnnouncementDao announcementDao = handle.attach(UserAnnouncementDao.class);
announcementDao.insert("guid1", testData.getUserId(), testData.getStudyId(), oldest.getTemplateId(), false, nowMillis - 1000);
announcementDao.insert("guid2", testData.getUserId(), testData.getStudyId(), msgTemplate.getTemplateId(), false, nowMillis);
return oldest;
});
assertAnnouncementsJson(testData.getUserGuid(), testData.getStudyGuid())
.statusCode(200)
.body("$.size()", equalTo(2))
.body("[0].message", equalTo(oldestTemplate.getTemplateText()))
.body("[1].message", equalTo(msgTemplate.getTemplateText()));
TransactionWrapper.useTxn(handle -> {
long numFound = handle.attach(UserAnnouncementDao.class)
.findAllForUserAndStudy(testData.getUserId(), testData.getStudyId())
.count();
assertEquals(0, numFound);
});
}
@Test
public void test_malformedContentStyle_returns400() {
assertAnnouncementsJson(testData.getUserGuid(), testData.getStudyGuid(), new Header(DDP_CONTENT_STYLE, "foobar"))
.statusCode(400)
.contentType(ContentType.JSON)
.body("code", equalTo(ErrorCodes.MALFORMED_HEADER))
.body("message", containsString("foobar"));
}
@Test
public void test_basicContentStyle() {
TransactionWrapper.useTxn(handle -> handle.attach(UserAnnouncementDao.class)
.insert(testData.getUserId(), testData.getStudyId(), msgTemplate.getTemplateId(), false));
assertAnnouncementsJson(testData.getUserGuid(), testData.getStudyGuid(), new Header(DDP_CONTENT_STYLE, ContentStyle.BASIC.name()))
.statusCode(200)
.body("$.size()", equalTo(1))
.body("[0].message", equalTo(msgPlainText));
}
@Test
public void test_permanentAnnouncements_notDeletedAfterRead() {
TransactionWrapper.useTxn(handle -> handle.attach(UserAnnouncementDao.class)
.insert(testData.getUserId(), testData.getStudyId(), msgTemplate.getTemplateId(), true));
String guid = assertAnnouncementsJson(testData.getUserGuid(), testData.getStudyGuid())
.statusCode(200)
.body("$.size()", equalTo(1))
.body("[0].guid", not(isEmptyOrNullString()))
.body("[0].permanent", equalTo(true))
.body("[0].message", equalTo(msgTemplate.getTemplateText()))
.extract().path("[0].guid");
TransactionWrapper.useTxn(handle -> {
List<UserAnnouncement> found = handle.attach(UserAnnouncementDao.class)
.findAllForUserAndStudy(testData.getUserId(), testData.getStudyId())
.collect(Collectors.toList());
assertEquals(1, found.size());
assertEquals(guid, found.get(0).getGuid());
});
assertAnnouncementsJson(testData.getUserGuid(), testData.getStudyGuid())
.statusCode(200)
.body("$.size()", equalTo(1))
.body("[0].guid", equalTo(guid));
}
@Test
public void test_formerProxy_stillGetMessages() {
StudyDto study = TransactionWrapper.withTxn(handle -> {
StudyDto testStudy = TestDataSetupUtil.generateTestStudy(handle, RouteTestUtil.getConfig());
handle.attach(JdbiClientUmbrellaStudy.class).insert(testData.getClientId(), testStudy.getId());
UserGovernanceDao userGovernanceDao = handle.attach(UserGovernanceDao.class);
Governance gov = userGovernanceDao.createGovernedUserWithGuidAlias(testData.getClientId(), testData.getUserId());
userGovernanceDao.grantGovernedStudy(gov.getId(), testStudy.getId());
handle.attach(JdbiUserStudyEnrollment.class)
.changeUserStudyEnrollmentStatus(gov.getGovernedUserId(), testStudy.getId(), EnrollmentStatusType.REGISTERED);
handle.attach(UserAnnouncementDao.class).insert(gov.getProxyUserId(), testStudy.getId(), msgTemplate.getTemplateId(), true);
userGovernanceDao.disableProxy(gov.getId());
return testStudy;
});
assertAnnouncementsJson(testData.getUserGuid(), study.getGuid())
.statusCode(200)
.body("$.size()", equalTo(1))
.body("[0].guid", not(isEmptyOrNullString()))
.body("[0].permanent", equalTo(true))
.body("[0].message", equalTo(msgTemplate.getTemplateText()));
TransactionWrapper.useTxn(handle -> {
handle.attach(UserAnnouncementDao.class).deleteAllForUserAndStudy(testData.getUserId(), study.getId());
handle.attach(UserGovernanceDao.class).deleteAllGovernancesForProxy(testData.getUserId());
});
}
private ValidatableResponse assertAnnouncementsJson(String userGuid, String studyGuid, Header... optionalHeaders) {
RequestSpecification request = given().auth().oauth2(token)
.pathParam("userGuid", userGuid)
.pathParam("studyGuid", studyGuid);
for (var header : optionalHeaders) {
request = request.header(header);
}
return request.when().get(url)
.then().assertThat()
.contentType(ContentType.JSON);
}
}
| 45.20082 | 138 | 0.665337 |
7e0a16d30422cfb828242eda4911e70581af930f | 2,910 | package com.zq.preparedStatement.crud;
import com.zq.bean.Customer;
import com.zq.util.JDBCUtils;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.*;
/**
* @author zhangqi
* 针对Customers表的查询操作
*/
public class CustomerForQuery {
@Test
public void testQueryCustomers() {
String sql="select id,name,email,birth from customers where id=?";
String sql1="select id,name,birth from customers where name=?";
Customer customer1 = queryCustomers(sql, 12);
Customer customer2 = queryCustomers(sql1, "王菲");
System.out.println(customer1);
System.out.println(customer2);
}
/**
* 针对customers表的查询通用操作
*/
public Customer queryCustomers(String sql, Object...args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = ps.getMetaData();
int columnCount = rsmd.getColumnCount();
if (rs.next()) {
Customer cust = new Customer();
for (int i = 0; i < columnCount; i++) {
// 获取列值
Object columnValue = rs.getObject(i + 1);
// 获取每个列的列名
String columnName = rsmd.getColumnName(i + 1);
// 给cust对象指定的columnName属性,赋值为columnValue(反射)
Field field = Customer.class.getDeclaredField(columnName);
field.setAccessible(true);
field.set(cust,columnValue);
}
return cust;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResources(conn,ps,rs);
}
return null;
}
@Test
public void testQuery1() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
String sql = "select id,name,email,birth from customers where id=?";
ps = conn.prepareStatement(sql);
ps.setObject(1, 1);
rs = ps.executeQuery();
if (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
String email = rs.getString(3);
Date birth = rs.getDate(4);
Customer customer = new Customer(id, name, email, birth);
System.out.println(customer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResources(conn, ps, rs);
}
}
}
| 28.811881 | 80 | 0.526117 |
0a69d0f7a21aa48f734f2e716ba11ef0ed0068f3 | 1,882 | package lmu.hradio.hradioshowcase.view.adapter;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import lmu.hradio.hradioshowcase.R;
import lmu.hradio.hradioshowcase.listener.TrackLikeService;
import lmu.hradio.hradioshowcase.util.DeviceUtils;
import lmu.hradio.hradioshowcase.view.fragment.playlist.PlaylistFragment;
public class PlayListFragmentPagerAdapter extends FragmentStatePagerAdapter {
private Fragment[] fragments;
private String blackListName;
private String likeListName;
private final int simultaneousPages;
public PlayListFragmentPagerAdapter(@NonNull FragmentManager fm, int behavior, TrackLikeService trackLikeService, Context context) {
super(fm, behavior);
fragments = new Fragment[2];
trackLikeService.getLikedTracks(playList -> fragments[0] = PlaylistFragment.newInstance(playList.getId()));
trackLikeService.getDislikedTracks(playList -> fragments[1] = PlaylistFragment.newInstance(playList.getId()));
blackListName = context.getString(R.string.dislike_list_name);
likeListName = context.getString(R.string.like_list_name);
simultaneousPages = DeviceUtils.isTablet(context) ? 2 : 1;
}
@Override public float getPageWidth(int position) {
return(1f/simultaneousPages);
}
@NonNull
@Override
public Fragment getItem(int position) {
return fragments[position];
}
@Override
public int getCount() {
return fragments.length;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0: return likeListName;
case 1: return blackListName;
default: return null;
}
}
}
| 32.448276 | 136 | 0.732731 |
26cc8236646749f67d9d1e4353c1590233d8865d | 352 | package com.seamlesspay.exception;
public class InvalidRequestException extends SPException {
private static final long serialVersionUID = 2L;
public InvalidRequestException(
String message,
String requestId,
Integer code,
Integer statusCode,
Throwable e) {
super(message, requestId, code, statusCode, e);
}
}
| 23.466667 | 58 | 0.71875 |
f0d947e991c2425ec0ea2fdc2af1f032219d2663 | 4,217 | package com.mbenabda.grafana.client;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mbenabda.grafana.client.exceptions.CantDeleteDashboardException;
import com.mbenabda.grafana.client.exceptions.DashboardDoesNotExistException;
import com.mbenabda.grafana.client.exceptions.GrafanaException;
import okhttp3.OkHttpClient;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.util.concurrent.TimeUnit.SECONDS;
public class GrafanaClientImpl implements GrafanaClient {
private final GrafanaService service;
private static final Logger LOGGER = Logger.getLogger(GrafanaClientImpl.class.getName());
private static final ObjectMapper mapper =
new ObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
public GrafanaClientImpl(GrafanaConfiguration configuration) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(configuration.host())
.client(configuration.auth()
.authorize(new OkHttpClient.Builder()
.writeTimeout(5, SECONDS)
.readTimeout(5, SECONDS)
.connectTimeout(1, SECONDS)
)
.build())
.addConverterFactory(JacksonConverterFactory.create(mapper))
.build();
service = retrofit.create(GrafanaService.class);
}
public void importDashboard(JsonNode dashboard)
throws GrafanaException, IOException {
Response<JsonNode> response = service.importDashboard(dashboard).execute();
if (!response.isSuccessful()) {
throw GrafanaException.withErrorBody(response.errorBody());
}
}
public void deleteDashboard(String slug)
throws GrafanaException,
IOException {
Response<JsonNode> response = service.deleteDashboard(slug).execute();
if (!response.isSuccessful()) {
if (response.code() == HTTP_NOT_FOUND) {
throw new DashboardDoesNotExistException("Dashboard " + slug + " does not exist");
}
throw CantDeleteDashboardException.withErrorBody(response.errorBody());
}
}
public JsonNode searchDashboard(String title) throws GrafanaException, IOException {
Response<List<JsonNode>> response = service.searchDashboard(title).execute();
if (response.isSuccessful()) {
if (response.body().size() == 1) {
return response.body().get(0);
} else {
throw new DashboardDoesNotExistException(
format(
"Expected to find 1 dashboard with title %s, found %s",
title, response.body().size())
);
}
} else if (response.code() == HTTP_NOT_FOUND) {
throw new DashboardDoesNotExistException(
"Dashboard " + title + " does not exist");
} else {
throw GrafanaException.withErrorBody(response.errorBody());
}
}
public String slug(String title) throws GrafanaException, IOException {
return searchDashboard(title).get("uri").asText().substring(3);
}
@Override
public boolean isAlive() {
try {
service.health().execute();
return true;
} catch (IOException e) {
return false;
}
}
}
| 37.651786 | 98 | 0.641926 |
394365ac979df27b28c292578e1cd0ea6b0a531d | 26,501 | package edu.cmu.cs.sb.stem;
import edu.cmu.cs.sb.chromviewer.*;
import edu.cmu.cs.sb.core.*;
import edu.umd.cs.piccolo.PCanvas;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.event.PZoomEventHandler;
import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
import edu.umd.cs.piccolo.nodes.PPath;
import edu.umd.cs.piccolox.PFrame;
import edu.umd.cs.piccolo.nodes.PText;
import edu.umd.cs.piccolo.nodes.PImage;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.net.*;
/**
* Class for the window that compares profiles
*/
public class CompareGui extends PFrame
{
/**
* Screen width
*/
static int SCREENWIDTH = 800;
/**
* Screen height
*/
static int SCREENHEIGHT = 600;
/**
* Space between edges and interface
*/
static int BUFFER = 135;
/**
* Offset for the caption parameter
*/
static int CAPOFFSET = 20;
/**
* constant for sorting profile pair by ID
*/
static int SORTID = 0;
/**
* constant for sorting profile pair by significance intersection
*/
static int SORTSIG = 1;
/**
* constant for sorting profile pair by suprise
*/
static int SORTSUPRISE = 2;
/**
* The canvas on which the signifcant profile pairs are displayed
*/
private PCanvas canvas;
/**
* The CompareInfo that this gui display
*/
CompareInfo theCompareInfo = null;
/**
* Array of the profiles associated with the original dataset
*/
private PNode[] profilenodes;
/**
* specifies how to sort profile pairs
*/
private int nsort= 0;
/**
* If the original and comparison data sets should be swapped from their original positions
*/
private boolean bswap = false;
/**
* Used to synchronize swapping actions
*/
private Object swaplock = new Object();
/**
* Label for the other data set in the layout whether it is the comparison or the original
*/
private String szother;
/**
* String for labels indicating if we have profile pairs or captions
*/
private String szprofileclusterCAP;
/**
* thegeneplotpanel associated with the original data set
*/
private GenePlotPanel thegeneplotpanel;
/**
* Interface options corresponding to data set indexed as rows in the comparison
*/
private GenePlotPanel rowplotpanel;
/**
* Interface options corresponding to data set currently indexed as columns in the comparison
*/
private GenePlotPanel colplotpanel;
/**
* The chromosome viewer object
*/
private ChromFrame cf;
/**
* Creates a comparison intersection interface backed on theCompareInfo
*/
public CompareGui(CompareInfo theCompareInfo,PNode[] profilenodes,
GenePlotPanel thegeneplotpanel,ChromFrame cf) throws Exception
{
super("Comparison - Significant Intersections", false, null);
this.theCompareInfo = theCompareInfo;
this.profilenodes = profilenodes;
this.thegeneplotpanel = thegeneplotpanel;
this.cf = cf;
if (theCompareInfo.origset.bkmeans)
{
szprofileclusterCAP = "Clusters";
}
else
{
szprofileclusterCAP = "Profiles";
}
}
/**
* Sorts rows based on reference profile most significant intersection p-value, then profile ID
*/
public static class SigRowComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
CompareInfo.CompareInfoRow cro1 = (CompareInfo.CompareInfoRow) o1;
CompareInfo.CompareInfoRow cro2 = (CompareInfo.CompareInfoRow) o2;
if (cro1.dminpval < cro2.dminpval)
return -1;
else if (cro1.dminpval > cro2.dminpval)
return 1;
else if (cro1.nprofile < cro2.nprofile)
return -1;
else if (cro1.nprofile > cro2.nprofile)
return 1;
return 0;
}
}
/**
* Sorts individual profiles by p-value with reference profile in row, then profile ID
*/
public static class SigComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
CompareInfo.CompareInfoRec co1 = (CompareInfo.CompareInfoRec) o1;
CompareInfo.CompareInfoRec co2 = (CompareInfo.CompareInfoRec) o2;
if (co1.dpval < co2.dpval)
return -1;
else if (co1.dpval > co2.dpval)
return 1;
else if (co1.nprofile < co2.nprofile)
return -1;
else if (co1.nprofile > co2.nprofile)
return 1;
return 0;
}
}
/**
* Sorts rows based on minimum correlation with reference profile, then profile ID
*/
public class SupriseComparator implements Comparator
{
int norigprofile;
SupriseComparator(int norigprofile)
{
this.norigprofile = norigprofile;
}
public int compare(Object o1, Object o2)
{
CompareInfo.CompareInfoRec co1 = (CompareInfo.CompareInfoRec) o1;
CompareInfo.CompareInfoRec co2 = (CompareInfo.CompareInfoRec) o2;
double dcorr1 = Util.correlation(
theCompareInfo.origset.modelprofiles[norigprofile],
theCompareInfo.comparesetfmnel.modelprofiles[co1.nprofile]);
double dcorr2 = Util.correlation(
theCompareInfo.origset.modelprofiles[norigprofile],
theCompareInfo.comparesetfmnel.modelprofiles[co2.nprofile]);
if (dcorr1 < dcorr2)
return -1;
else if (dcorr1 > dcorr2)
return 1;
else if (co1.nprofile < co2.nprofile)
return -1;
else if (co1.nprofile > co2.nprofile)
return 1;
return 0;
}
}
/**
* Sorts rows based on minimum correlation with reference profile, then profile ID
*/
public static class SupriseRowComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
CompareInfo.CompareInfoRow cro1 = (CompareInfo.CompareInfoRow) o1;
CompareInfo.CompareInfoRow cro2 = (CompareInfo.CompareInfoRow) o2;
if (cro1.dmincorr < cro2.dmincorr)
return -1;
else if (cro1.dmincorr > cro2.dmincorr)
return 1;
else if (cro1.nprofile < cro2.nprofile)
return -1;
else if (cro1.nprofile > cro2.nprofile)
return 1;
return 0;
}
}
/**
* sets the size of the PFrame
*/
public void beforeInitialize()
{
setSize(SCREENWIDTH,SCREENHEIGHT);
}
/**
* Simply calls drawcomparemain
*/
public void initialize()
{
drawcomparemain();
}
/**
* Lays out the comparison panel
*/
public void drawcomparemain()
{
canvas = getCanvas();
canvas.getLayer().removeAllChildren();
int nmaxcol = 0;
float frecwidth = (float) 150.0;
int OFFSET = 0;
ArrayList sigrows;
final STEM_DataSet rowset, colset;
PNode[] rownodes, colnodes;
String sztexttop, sztextleft;
synchronized (swaplock)
{
if (bswap)
{
sigrows = theCompareInfo.sigrowsswap;
colset = theCompareInfo.origset;
rowset = theCompareInfo.comparesetfmnel;
rowplotpanel = theCompareInfo.compareframe.thegeneplotpanel;
colplotpanel = thegeneplotpanel;
colnodes = profilenodes;
rownodes = theCompareInfo.compareframe.profilenodes;
sztexttop = "Original Set "+szprofileclusterCAP;
sztextleft = "Comparison Set "+szprofileclusterCAP;
szother = "comparison";
}
else
{
sigrows = theCompareInfo.sigrows;
rowset = theCompareInfo.origset;
colset = theCompareInfo.comparesetfmnel;
rownodes = profilenodes;
colnodes = theCompareInfo.compareframe.profilenodes;
colplotpanel = theCompareInfo.compareframe.thegeneplotpanel;
rowplotpanel = thegeneplotpanel;
sztextleft = "Original Set "+szprofileclusterCAP;
sztexttop = "Comparison Set "+szprofileclusterCAP;
szother = "original";
}
}
PText comparetext = new PText(sztexttop);
comparetext.setFont(new Font("times",Font.PLAIN,14));
comparetext.translate(3.0*SCREENWIDTH/18.0,0);
canvas.getLayer().addChild(comparetext);
PText originaltext = new PText(sztextleft);
originaltext.setFont(new Font("times",Font.PLAIN,14));
originaltext.translate(0,SCREENHEIGHT/2.0);
originaltext.rotate(-Math.PI/2);
canvas.getLayer().addChild(originaltext);
int nsigrows = sigrows.size();
if (nsigrows >= 2)
{
PText comparetext2 = new PText(sztexttop);
comparetext2.setFont(new Font("times",Font.PLAIN,14));
comparetext2.translate(12.0*SCREENWIDTH/18.0,0);
canvas.getLayer().addChild(comparetext2);
PText originaltext2 = new PText(sztextleft);
originaltext2.setFont(new Font("times",Font.PLAIN,14));
originaltext2.translate(SCREENWIDTH/2.0+CAPOFFSET,SCREENHEIGHT/2.0);
originaltext2.rotate(-Math.PI/2);
canvas.getLayer().addChild(originaltext2);
}
for (int nrow = 0; nrow < nsigrows; nrow++)
{
CompareInfo.CompareInfoRow cir = (CompareInfo.CompareInfoRow) sigrows.get(nrow);
if (cir.sigprofiles.size() >= nmaxcol)
{
nmaxcol = cir.sigprofiles.size();
}
}
CompareInfo.CompareInfoRow[] sigrowsArray = new CompareInfo.CompareInfoRow[nsigrows];
for (int nrowindex = 0; nrowindex < sigrowsArray.length; nrowindex++)
{
sigrowsArray[nrowindex] = (CompareInfo.CompareInfoRow) sigrows.get(nrowindex);
}
if (nsort == SORTSIG)
{
Arrays.sort(sigrowsArray, new SigRowComparator());
}
else if (nsort == SORTSUPRISE)
{
Arrays.sort(sigrowsArray, new SupriseRowComparator());
}
double dheight =20;
if (nsigrows > 0)
{
dheight = Math.max(Math.min((SCREENHEIGHT-BUFFER)*2/nsigrows,(SCREENWIDTH/2-BUFFER)/(nmaxcol+1)),20);
}
for (int nrow = 0; nrow < nsigrows; nrow++)
{
double dxoffset, dyoffset;
final CompareInfo.CompareInfoRow cir = (CompareInfo.CompareInfoRow) sigrowsArray[nrow];
PNode node = (PNode) rownodes[cir.nprofile].clone();
node.scale((dheight)/(node.getScale()*node.getHeight()));
if (nrow < Math.ceil(nsigrows/2.0))
{
dxoffset = CAPOFFSET/node.getScale();
dyoffset = node.getHeight()*nrow+CAPOFFSET/node.getScale();
}
else
{
dxoffset =1/node.getScale()*SCREENWIDTH/2+2*CAPOFFSET/node.getScale();
dyoffset = node.getHeight()*(nrow-Math.ceil(nsigrows/2.0))+CAPOFFSET/node.getScale();
}
String szcountLabel = "" +(int) rowset.countassignments[cir.nprofile];
PText counttext = new PText(szcountLabel);
counttext.setFont(new Font("times",Font.PLAIN,(int) (Math.ceil(node.getHeight()/6))));
counttext.translate(1,node.getHeight()-node.getHeight()/4);
node.addChild(counttext);
node.translate(dxoffset, dyoffset);
if (nrow == 0)
{
double dwidth = (float)(node.getWidth()*node.getScale());
double dtheight = Math.ceil(nsigrows/2.0)*(float)(node.getHeight()*node.getScale());
PNode line = PPath.createRectangle((float) (CAPOFFSET+dwidth+1.5*node.getScale()),
(float) CAPOFFSET,
(float) (6*node.getScale()),
(float) (dtheight));
line.setPaint(ST.buttonColor);
canvas.getLayer().addChild(line);
}
else if (nrow == Math.ceil(nsigrows/2.0))
{
double dscale = node.getScale();
double dwidth = (float)(node.getWidth()*dscale);
double dtheight = (nsigrows-Math.ceil(nsigrows/2.0))*(float)(node.getHeight()*dscale);
PNode linemid = PPath.createRectangle((float) (2*CAPOFFSET+dwidth+SCREENWIDTH/2.0+1.5*dscale),
(float) CAPOFFSET,(float) (6*dscale),
(float) (dtheight));
linemid.setPaint(ST.buttonColor);
canvas.getLayer().addChild(linemid);
float flast =(float)((CAPOFFSET/dscale+10+node.getHeight()*(nmaxcol+1))*dscale);
float fmid = (float)(flast + (SCREENWIDTH/2.0+CAPOFFSET/dscale-flast)/2);
PNode line = PPath.createRectangle(fmid,
(float) 5,(float) (6*dscale), (float) (SCREENHEIGHT-BUFFER+15));
line.setPaint(ST.lightBlue);
canvas.getLayer().addChild(line);
}
node.addInputEventListener(new PBasicInputEventHandler()
{
public void mousePressed(PInputEvent event)
{
if (event.getButton() == MouseEvent.BUTTON1)
{
ProfileGui pg;
pg = new ProfileGui(rowset,cir.nprofile,null,null,-1,null,null,null,rowplotpanel,cf);
pg.setLocation(20,50);
pg.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pg.setSize(new Dimension(SCREENWIDTH,SCREENHEIGHT));
pg.setVisible(true);
}
}
});
canvas.getLayer().addChild(node);
ArrayList compareprofiles = cir.sigprofiles;
int ncols = compareprofiles.size();
//resort columns
CompareInfo.CompareInfoRec[] cirecArray = new CompareInfo.CompareInfoRec[ncols];
for (int ncolindex = 0; ncolindex < cirecArray.length; ncolindex++)
{
cirecArray[ncolindex] = (CompareInfo.CompareInfoRec) compareprofiles.get(ncolindex);
}
if (nsort == SORTSIG)
{
Arrays.sort(cirecArray, new SigComparator());
}
else if (nsort == SORTSUPRISE)
{
Arrays.sort(cirecArray, new SupriseComparator(cir.nprofile));
}
for (int ncolindex = 0; ncolindex < ncols; ncolindex++)
{
final CompareInfo.CompareInfoRec cirec = (CompareInfo.CompareInfoRec) cirecArray[ncolindex];
PNode colnode = (PNode) colnodes[cirec.nprofile].clone();
colnode.scale((dheight)/(colnode.getScale()*colnode.getHeight()));
colnode.translate(10+dxoffset+colnode.getHeight()*(ncolindex+1), dyoffset);
String szLabel = ((int) cirec.dmatch)+";"+MAINGUI2.doubleToSz(cirec.dpval);
PText text = new PText(szLabel);
text.setFont(new Font("times",Font.PLAIN,(int) (Math.ceil(colnode.getHeight()/6))));
text.translate(1,3*colnode.getHeight()/4);
colnode.addChild(text);
NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
String szcorrLabel = nf.format(cirec.dcorrval);
PText corrtext = new PText(szcorrLabel);
corrtext.setFont(new Font("times",Font.PLAIN,(int) (Math.ceil(colnode.getHeight()/6))));
corrtext.translate(4*colnode.getWidth()/7,-1);
colnode.addChild(corrtext);
final String szIntersect = MAINGUI2.doubleToSz(cirec.dmatch)+" of the "+
MAINGUI2.doubleToSz(rowset.countassignments[cir.nprofile])
+" genes assigned to Profile "
+cir.nprofile+" in the " + szother +
" experiment were also assigned to this profile (p-value ="
+MAINGUI2.doubleToSz(cirec.dpval)+")";
colnode.addInputEventListener(new PBasicInputEventHandler()
{
public void mousePressed(PInputEvent event)
{
if (event.getButton() == MouseEvent.BUTTON1)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
ProfileGui pg;
pg = new ProfileGui(colset ,cirec.nprofile,null,
cirec.inames,cir.nprofile,szIntersect,null,null,colplotpanel,cf);
pg.setLocation(20,50);
pg.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pg.setSize(new Dimension(SCREENWIDTH,SCREENHEIGHT));
pg.setVisible(true);
}
});
}
}
});
canvas.getLayer().addChild(colnode);
}
}
PNode supriseButton = PPath.createRectangle((float) 0.0,(float) 0.0,frecwidth,(float) 18.0);
supriseButton.translate(4*(SCREENWIDTH+OFFSET)/5-100,SCREENHEIGHT-65);
PText thesupriseText = new PText("Order By Correlation");
thesupriseText.setFont(new Font("times",Font.PLAIN,12));
thesupriseText.translate(23,2);
supriseButton.setPaint(ST.buttonColor);
supriseButton.addChild(thesupriseText);
canvas.getLayer().addChild(supriseButton);
supriseButton.addInputEventListener(new PBasicInputEventHandler()
{
public void mousePressed(PInputEvent event)
{
nsort = SORTSUPRISE;
drawcomparemain();
//repaint();
}
});
PImage helpButton = new PImage(Util.getImageURL("Help24.gif"));
canvas.getLayer().addChild(helpButton);
helpButton.translate(SCREENWIDTH-70,SCREENHEIGHT-68);
final CompareGui thisFrame = this;
helpButton.addInputEventListener(new PBasicInputEventHandler()
{
public void mousePressed(PInputEvent event)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JDialog helpDialog = new JDialog(thisFrame, "Help", false);
Container theHelpDialogPane = helpDialog.getContentPane();
helpDialog.setBackground(Color.white);
theHelpDialogPane.setBackground(Color.white);
String szMessage;
if (rowset.bkmeans)
{
szMessage =
"The display shows to the left of the yellow line a K-means cluster from one of the data "+
"sets. To the right of the yellow line are K-means clusters from the other data set for which a significant "+
"number of genes assigned to the cluster on left were also assigned to it. "+
"The p-value of the number of genes in the intersection is computed using the hypergeometric "+
"distribution based on the number of total genes assigned to each of the two clusters, and the "+
"total number of genes on the array.\n\n"+
"The display is split in half by a blue line, there is no difference between clusters to the left and right "+
"of the blue line. The clusters in the display can be reordered based on the significance through the "+
"'Order by Significance' option. Within "+
"each row the clusters are ordered in decreasing order of significance. The rows are reordered based on "+
"decreasing significance of the most significant intersection for the row. 'Order by Correlation' is "+
"similar but instead of re-ordering based on significance, the re-ordering is done based on correlation, "+
"so that one can quickly identify dissimilar pairs of clusters. 'Order by ID' is the default method to "+
"order clusters, based on increasing cluster ID. "+
"'Swap Rows and Columns' swaps which data set has clusters to the left of the yellow line and "+
"which data set has clusters organized in columns to the right of the yellow line.\n\n"+
"Note also the main interface is zoomable and pannable, "+
"hold the right button down to zoom or the left to pan while moving the mouse.";
}
else
{
szMessage = "The display shows to the left of the yellow line a profile from one of the data "+
"sets. To the right of the yellow line are profiles from the other data set for which a significant "+
"number of genes assigned to the profile on left were also assigned to it. "+
"The p-value of the number of genes in the intersection is computed using the hypergeometric "+
"distribution based on the number of total genes assigned to each of the two profiles, and the "+
"total number of genes on the array.\n\n"+
"The display is split in half by a blue line, there is no difference between profiles to the left and right "+
"of the blue line. The profiles in the display can be reordered based on the significance through the "+
"'Order by Significance' option. Within "+
"each row the profiles are ordered in decreasing order of significance. The rows are reordered based on "+
"decreasing significance of the most significant intersection for the row. 'Order by Correlation' is "+
"similar but instead of re-ordering based on significance, the re-ordering is done based on correlation, "+
"so that one can quickly identify dissimilar pairs of profiles. 'Order by ID' is the default method to "+
"order profiles, based on increasing profile ID. "+
"'Swap Rows and Columns' swaps which data set has profiles to the left of the yellow line and "+
"which data set has profiles organized in columns to the right of the yellow line.\n\n"+
"Note also the main interface is zoomable and pannable, "+
"hold the right button down to zoom or the left to pan while moving the mouse.";
}
JTextArea textArea = new JTextArea(szMessage,9,60);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setBackground(Color.white);
textArea.setEditable(false);
ImageIcon ii;
if (rowset.bkmeans)
{
ii = Util.createImageIcon("p6_2.png");
}
else
{
ii = Util.createImageIcon("p38_13.png");
}
JLabel jl = new JLabel(ii);
theHelpDialogPane.add(jl);
JPanel psl = new JPanel();
psl.setLayout(new SpringLayout());
psl.setBackground(Color.white);
psl.add(jl);
JScrollPane jsp2 = new JScrollPane(textArea);
psl.add(jsp2);
SpringUtilities.makeCompactGrid(psl,2,1,2,2,2,2);
JScrollPane jsp =new JScrollPane(psl);
theHelpDialogPane.add(jsp);
theHelpDialogPane.setSize(800,600);
theHelpDialogPane.validate();
helpDialog.setLocation(thisFrame.getX()+25,thisFrame.getY()+25);
helpDialog.setSize(800,600);
helpDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
helpDialog.setVisible(true);
}
});
}
});
PNode idButton = PPath.createRectangle((float) 0.0,(float) 0.0,frecwidth,(float) 18.0);
idButton.translate(2*(SCREENWIDTH+OFFSET)/5-100,SCREENHEIGHT-65);
PText theidText = new PText("Order By Profile ID");
theidText.setFont(new Font("times",Font.PLAIN,12));
theidText.translate(25,2);
idButton.setPaint(ST.buttonColor);
idButton.addChild(theidText);
idButton.addInputEventListener(new PBasicInputEventHandler()
{
public void mousePressed(PInputEvent event)
{
nsort = SORTID;
drawcomparemain();
}
});
canvas.getLayer().addChild(idButton);
canvas.getLayer().addChild(idButton);
PNode sigButton = PPath.createRectangle((float) 0.0,(float) 0.0,(float) frecwidth,(float) 18.0);
sigButton.translate(3*(SCREENWIDTH+OFFSET)/5-100,SCREENHEIGHT-65);
PText thesigText = new PText("Order By Significance");
thesigText.setFont(new Font("times",Font.PLAIN,12));
thesigText.translate(20,2);
sigButton.setPaint(ST.buttonColor);
sigButton.addChild(thesigText);
canvas.getLayer().addChild(sigButton);
sigButton.addInputEventListener(new PBasicInputEventHandler()
{
public void mousePressed(PInputEvent event)
{
nsort = SORTSIG;
drawcomparemain();
}
});
PNode swapButton = PPath.createRectangle((float) 0.0,(float) 0.0,frecwidth,(float) 18.0);
swapButton.translate(1*(SCREENWIDTH+OFFSET)/5-100,SCREENHEIGHT-65);
PText theswapText = new PText("Swap Rows and Columns");
theswapText.setFont(new Font("times",Font.PLAIN,12));
theswapText.translate(6,2);
swapButton.setPaint(ST.buttonColor);
swapButton.addChild(theswapText);
canvas.getLayer().addChild(swapButton);
swapButton.addInputEventListener(new PBasicInputEventHandler()
{
public void mousePressed(PInputEvent event)
{
synchronized(swaplock)
{
bswap = !bswap;
}
drawcomparemain();
}
});
}
}
| 37.697013 | 136 | 0.589638 |
50daf1cc658799acdf97d6f27ecd90210260d5bd | 945 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.threatconnect.sdk.server.response.service.association;
import com.threatconnect.sdk.server.response.service.ApiServiceResponse;
import com.threatconnect.sdk.server.response.service.ApiServiceResponse;
/**
*
* @author James
*/
public class DissociateServiceResponse extends ApiServiceResponse
{
public DissociateServiceResponse(String type, String name, String modifier)
{
super(type + " \"" + name + "\" association removed from " + modifier, true);
}
public DissociateServiceResponse(String type, String name)
{
super(type + " \"" + name + "\" association removed", true);
}
public DissociateServiceResponse(String type)
{
super(type + " association removed", true);
}
}
| 28.636364 | 85 | 0.703704 |
71a2dcd10089ad60cf711898101e81b5a18cbb39 | 23,371 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.masterdb.security.hibernate;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.id.ExternalId;
import com.opengamma.id.UniqueId;
import com.opengamma.master.security.ManageableSecurity;
import com.opengamma.masterdb.security.hibernate.bond.CouponTypeBean;
import com.opengamma.masterdb.security.hibernate.bond.GuaranteeTypeBean;
import com.opengamma.masterdb.security.hibernate.bond.IssuerTypeBean;
import com.opengamma.masterdb.security.hibernate.bond.MarketBean;
import com.opengamma.masterdb.security.hibernate.bond.YieldConventionBean;
import com.opengamma.masterdb.security.hibernate.equity.GICSCodeBean;
import com.opengamma.masterdb.security.hibernate.future.BondFutureTypeBean;
import com.opengamma.masterdb.security.hibernate.future.CashRateTypeBean;
import com.opengamma.masterdb.security.hibernate.future.CommodityFutureTypeBean;
import com.opengamma.masterdb.security.hibernate.future.FutureBundleBean;
import com.opengamma.masterdb.security.hibernate.future.FutureSecurityBean;
import com.opengamma.masterdb.security.hibernate.future.UnitBean;
import com.opengamma.util.monitor.OperationTimer;
/**
* HibernateSecurityMaster session and utility methods implementation.
*
*/
public class HibernateSecurityMasterSession implements HibernateSecurityMasterDao {
/** Logger. */
private static final Logger s_logger = LoggerFactory.getLogger(HibernateSecurityMasterSession.class);
/**
* The Hibernate session.
*/
private Session _session;
/**
* Creates an instance with a session.
* @param session the session, not null
*/
public HibernateSecurityMasterSession(Session session) {
_session = session;
}
//-------------------------------------------------------------------------
/**
* Gets the Hibernate session.
* @return the session, not null
*/
public Session getSession() {
return _session;
}
//-------------------------------------------------------------------------
// UTILITY METHODS
private <T extends EnumBean> T persistBean(T bean) {
Long id = (Long) getSession().save(bean);
getSession().flush();
bean.setId(id);
return bean;
}
// SESSION LEVEL METHODS
// Exchanges
@Override
public ExchangeBean getOrCreateExchangeBean(String name,
String description) {
Query query = getSession().getNamedQuery("ExchangeBean.one");
query.setString("name", name);
ExchangeBean exchange = (ExchangeBean) query.uniqueResult();
if (exchange == null) {
exchange = persistBean(new ExchangeBean(name, description));
} else {
if (description != null) {
if (exchange.getDescription() == null) {
exchange.setDescription(description);
getSession().saveOrUpdate(exchange);
getSession().flush();
}
}
}
return exchange;
}
@SuppressWarnings("unchecked")
@Override
public List<ExchangeBean> getExchangeBeans() {
Query query = getSession().getNamedQuery("ExchangeBean.all");
return query.list();
}
// Currencies
@Override
public CurrencyBean getOrCreateCurrencyBean(String name) {
Query query = getSession().getNamedQuery("CurrencyBean.one");
query.setString("name", name);
CurrencyBean currency = (CurrencyBean) query.uniqueResult();
if (currency == null) {
currency = persistBean(new CurrencyBean(name));
}
return currency;
}
@SuppressWarnings("unchecked")
@Override
public List<CurrencyBean> getCurrencyBeans() {
Query query = getSession().getNamedQuery("CurrencyBean.all");
return query.list();
}
// GICS codes
@Override
public GICSCodeBean getOrCreateGICSCodeBean(final String name,
final String description) {
Query query = getSession().getNamedQuery("GICSCodeBean.one");
query.setString("name", name);
GICSCodeBean gicsCode = (GICSCodeBean) query.uniqueResult();
if (gicsCode == null) {
gicsCode = persistBean(new GICSCodeBean(name, description));
} else {
if (description != null) {
if (gicsCode.getDescription() == null) {
gicsCode.setDescription(description);
getSession().saveOrUpdate(gicsCode);
getSession().flush();
}
}
}
return gicsCode;
}
@SuppressWarnings("unchecked")
@Override
public List<GICSCodeBean> getGICSCodeBeans() {
Query query = getSession().getNamedQuery("GICSCodeBean.all");
return query.list();
}
// Daycount conventions
@Override
public DayCountBean getOrCreateDayCountBean(final String convention) {
final Query query = getSession().getNamedQuery("DayCountBean.one");
query.setString("name", convention);
DayCountBean bean = (DayCountBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new DayCountBean(convention));
}
return bean;
}
@SuppressWarnings ("unchecked")
@Override
public List<DayCountBean> getDayCountBeans() {
final Query query = getSession().getNamedQuery("DayCountBean.all");
return query.list();
}
// Business day conventions
@Override
public BusinessDayConventionBean getOrCreateBusinessDayConventionBean(final String convention) {
final Query query = getSession().getNamedQuery("BusinessDayConventionBean.one");
query.setString("name", convention);
BusinessDayConventionBean bean = (BusinessDayConventionBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new BusinessDayConventionBean(convention));
}
return bean;
}
@SuppressWarnings("unchecked")
@Override
public List<BusinessDayConventionBean> getBusinessDayConventionBeans() {
return getBeansFromNamedQuery("BusinessDayConventionBean.all");
}
@SuppressWarnings("rawtypes")
private List getBeansFromNamedQuery(String namedQuery) {
final Query query = getSession().getNamedQuery(namedQuery);
return query.list();
}
// Frequencies
@Override
public FrequencyBean getOrCreateFrequencyBean(final String convention) {
final Query query = getSession().getNamedQuery("FrequencyBean.one");
query.setString("name", convention);
FrequencyBean bean = (FrequencyBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new FrequencyBean(convention));
}
return bean;
}
@SuppressWarnings ("unchecked")
@Override
public List<FrequencyBean> getFrequencyBeans() {
return getBeansFromNamedQuery("FrequencyBean.all");
}
// CommodityFutureTypes
@Override
public CommodityFutureTypeBean getOrCreateCommodityFutureTypeBean(final String type) {
final Query query = getSession().getNamedQuery("CommodityFutureTypeBean.one");
query.setString("name", type);
CommodityFutureTypeBean bean = (CommodityFutureTypeBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new CommodityFutureTypeBean(type));
}
return bean;
}
@SuppressWarnings ("unchecked")
@Override
public List<CommodityFutureTypeBean> getCommodityFutureTypeBeans() {
return getBeansFromNamedQuery("CommodityFutureTypeBean.all");
}
// BondFutureType
@Override
public BondFutureTypeBean getOrCreateBondFutureTypeBean(final String type) {
final Query query = getSession().getNamedQuery("BondFutureTypeBean.one");
query.setString("name", type);
BondFutureTypeBean bean = (BondFutureTypeBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new BondFutureTypeBean(type));
}
return bean;
}
@SuppressWarnings ("unchecked")
@Override
public List<BondFutureTypeBean> getBondFutureTypeBeans() {
return getBeansFromNamedQuery("BondFutureTypeBean.all");
}
// UnitName
@Override
public UnitBean getOrCreateUnitNameBean(final String unitName) {
final Query query = getSession().getNamedQuery("UnitBean.one");
query.setString("name", unitName);
UnitBean bean = (UnitBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new UnitBean(unitName));
}
return bean;
}
@SuppressWarnings ("unchecked")
@Override
public List<UnitBean> getUnitNameBeans() {
return getBeansFromNamedQuery("UnitBean.all");
}
// CashRateType
@Override
public CashRateTypeBean getOrCreateCashRateTypeBean(final String type) {
final Query query = getSession().getNamedQuery("CashRateTypeBean.one");
query.setString("name", type);
CashRateTypeBean bean = (CashRateTypeBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new CashRateTypeBean(type));
}
return bean;
}
@SuppressWarnings ("unchecked")
@Override
public List<CashRateTypeBean> getCashRateTypeBeans() {
return getBeansFromNamedQuery("CashRateTypeBean.all");
}
// IssuerTypeBean
@Override
public IssuerTypeBean getOrCreateIssuerTypeBean(final String type) {
final Query query = getSession().getNamedQuery("IssuerTypeBean.one");
query.setString("name", type);
IssuerTypeBean bean = (IssuerTypeBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new IssuerTypeBean(type));
}
return bean;
}
@SuppressWarnings ("unchecked")
@Override
public List<IssuerTypeBean> getIssuerTypeBeans() {
return getBeansFromNamedQuery("IssuerTypeBean.all");
}
// MarketBean
@Override
public MarketBean getOrCreateMarketBean(final String market) {
final Query query = getSession().getNamedQuery("MarketBean.one");
query.setString("name", market);
MarketBean bean = (MarketBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new MarketBean(market));
}
return bean;
}
@SuppressWarnings("unchecked")
@Override
public List<MarketBean> getMarketBeans() {
return getBeansFromNamedQuery("MarketBean.all");
}
// YieldConventionBean
@Override
public YieldConventionBean getOrCreateYieldConventionBean(final String convention) {
final Query query = getSession().getNamedQuery("YieldConventionBean.one");
query.setString("name", convention);
YieldConventionBean bean = (YieldConventionBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new YieldConventionBean(convention));
}
return bean;
}
@SuppressWarnings("unchecked")
@Override
public List<YieldConventionBean> getYieldConventionBeans() {
return getBeansFromNamedQuery("YieldConventionBean.all");
}
// GuaranteeTypeBean
@Override
public GuaranteeTypeBean getOrCreateGuaranteeTypeBean(final String type) {
final Query query = getSession().getNamedQuery("GuaranteeTypeBean.one");
query.setString("name", type);
GuaranteeTypeBean bean = (GuaranteeTypeBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new GuaranteeTypeBean(type));
}
return bean;
}
@SuppressWarnings("unchecked")
@Override
public List<GuaranteeTypeBean> getGuaranteeTypeBeans() {
return getBeansFromNamedQuery("GuaranteeTypeBean.all");
}
// CouponTypeBean
@Override
public CouponTypeBean getOrCreateCouponTypeBean(final String type) {
final Query query = getSession().getNamedQuery("CouponTypeBean.one");
query.setString("name", type);
CouponTypeBean bean = (CouponTypeBean) query.uniqueResult();
if (bean == null) {
bean = persistBean(new CouponTypeBean(type));
}
return bean;
}
@SuppressWarnings ("unchecked")
@Override
public List<CouponTypeBean> getCouponTypeBeans() {
return getBeansFromNamedQuery("CouponTypeBean.all");
}
// Identifiers
private IdentifierAssociationBean createIdentifierAssociationBean(Date now, String scheme, String identifier, SecurityBean security) {
final IdentifierAssociationBean association = new IdentifierAssociationBean(security, new ExternalIdBean(scheme, identifier));
Query query = getSession().getNamedQuery("IdentifierAssociationBean.one.previousAssociation");
query.setString("scheme", scheme);
query.setString("identifier", identifier);
query.setTimestamp("now", now);
IdentifierAssociationBean other = (IdentifierAssociationBean) query.uniqueResult();
if (other != null) {
association.setValidStartDate(other.getValidEndDate());
}
query = getSession().getNamedQuery("IdentifierAssociationBean.one.nextAssociation");
query.setString("scheme", scheme);
query.setString("identifier", identifier);
query.setTimestamp("now", now);
other = (IdentifierAssociationBean) query.uniqueResult();
if (other != null) {
association.setValidEndDate(other.getValidEndDate());
}
Long id = (Long) getSession().save(association);
association.setId(id);
getSession().flush();
return association;
}
@Override
public IdentifierAssociationBean getCreateOrUpdateIdentifierAssociationBean(
Date now, String scheme, String identifier, SecurityBean security) {
Query query = getSession().getNamedQuery(
"IdentifierAssociationBean.one.byDateIdentifier");
query.setString("scheme", scheme);
query.setString("identifier", identifier);
query.setTimestamp("now", now);
IdentifierAssociationBean association = (IdentifierAssociationBean) query.uniqueResult();
if (association == null) {
association = createIdentifierAssociationBean(now, scheme, identifier, security);
} else {
if (!association.getSecurity().getId().equals(security.getId())) {
// terminate the previous record, and create a new one
association.setValidEndDate(now);
getSession().update(association);
getSession().flush();
association = createIdentifierAssociationBean(now, scheme, identifier, security);
}
}
return association;
}
// only for testing.
@SuppressWarnings ("unchecked")
protected List<IdentifierAssociationBean> getAllAssociations() {
Query query = getSession().createQuery(
"from IdentifierAssociationBean as d");
return query.list();
}
@Override
public void associateOrUpdateExternalIdWithSecurity(Date now,
ExternalId identifier, SecurityBean security) {
getCreateOrUpdateIdentifierAssociationBean(now, identifier
.getScheme().getName(), identifier.getValue(), security); // TODO: was .getFirstVersion()
}
// Generic Securities
@Override
public SecurityBean getSecurityBean(final ManageableSecurity base, SecurityBeanOperation<?, ?> beanOperation) {
String beanType = beanOperation.getBeanClass().getSimpleName();
Query query = getSession().getNamedQuery(beanType + ".one.bySecurityId");
query.setLong("securityId", extractRowId(base.getUniqueId()));
return (SecurityBean) query.uniqueResult();
}
// Specific securities through BeanOperation
@Override
public <S extends ManageableSecurity, SBean extends SecurityBean> SBean createSecurityBean(
final OperationContext context, final SecurityBeanOperation<S, SBean> beanOperation, final Date effectiveDateTime, final S security) {
final SBean bean = beanOperation.createBean(context, this, security);
bean.setSecurityId(extractRowId(security.getUniqueId()));
persistSecurityBean(context, bean);
beanOperation.postPersistBean(context, this, effectiveDateTime, bean);
return bean;
}
@Override
public SecurityBean persistSecurityBean(final OperationContext context, final SecurityBean bean) {
final Long id = (Long) getSession().save(bean);
bean.setId(id);
getSession().flush();
return bean;
}
// Debug/testing
@SuppressWarnings("unchecked")
@Override
public <T extends SecurityBean> List<T> getAllSecurityBeans(final Class<T> beanClass) {
String beanName = beanClass.getName();
beanName = beanName.substring(beanName.lastIndexOf('.') + 1);
return getSession().getNamedQuery(beanName + ".all").list();
}
// Equities
// Internal query methods for equities
/*
* @SuppressWarnings("unchecked")
*
* @Override
* public List<EquitySecurityBean> getEquitySecurityBeans() {
* Query query = getSession().getNamedQuery("EquitySecurityBean.all");
* return query.list();
* }
*
* @SuppressWarnings("unchecked")
*
* @Override
* public List<EquitySecurityBean> getAllVersionsOfEquitySecurityBean(
* EquitySecurityBean firstVersion) {
* Query query = getSession().getNamedQuery(
* "EquitySecurityBean.many.allVersionsByFirstVersion");
* query.setParameter("firstVersion", firstVersion);
* return query.list();
* }
*
* @Override
* public EquitySecurityBean getCurrentEquitySecurityBean(Date now,
* ExchangeBean exchange, String companyName, CurrencyBean currency) {
* Query query = getSession().getNamedQuery(
* "EquitySecurityBean.one.byExchangeCompanyNameCurrencyDate");
* query.setDate("now", now);
* query.setParameter("exchange", exchange);
* query.setString("companyName", companyName);
* query.setParameter("currency", currency);
* return (EquitySecurityBean) query.uniqueResult();
* }
*
* @Override
* public EquitySecurityBean getCurrentEquitySecurityBean(Date now,
* EquitySecurityBean firstVersion) {
* Query query = getSession().getNamedQuery(
* "EquitySecurityBean.one.byFirstVersionDate");
* query.setParameter("firstVersion", firstVersion);
* query.setDate("now", now);
* return (EquitySecurityBean) query.uniqueResult();
* }
*
* @Override
* public EquitySecurityBean getCurrentLiveEquitySecurityBean(Date now,
* ExchangeBean exchange, String companyName, CurrencyBean currency) {
* Query query = getSession().getNamedQuery(
* "EquitySecurityBean.one.liveByExchangeCompanyNameCurrencyDate");
* query.setParameter("exchange", exchange);
* query.setString("companyName", companyName);
* query.setParameter("currency", currency);
* query.setDate("now", now);
* return (EquitySecurityBean) query.uniqueResult();
* }
*
* @Override
* public EquitySecurityBean getCurrentLiveEquitySecurityBean(Date now,
* EquitySecurityBean firstVersion) {
* Query query = getSession().getNamedQuery(
* "EquitySecurityBean.one.liveByFirstVersionDate");
* query.setParameter("firstVersion", firstVersion);
* query.setDate("now", now);
* return (EquitySecurityBean) query.uniqueResult();
* }
*/
// Equity options
/*
* @SuppressWarnings("unchecked")
*
* @Override
* public List<OptionSecurityBean> getEquityOptionSecurityBeans() {
* Query query = getSession().getNamedQuery("EquityOptionSecurityBean.all");
* return query.list();
* }
*/
/*
* @SuppressWarnings("unchecked")
*
* @Override
* public List<OptionSecurityBean> getOptionSecurityBeans() {
* Query query = getSession().getNamedQuery("OptionSecurityBean.all");
* return query.list();
* }
*/
// Futures
@SuppressWarnings("unchecked")
@Override
public List<FutureBundleBean> getFutureBundleBeans(Date now, FutureSecurityBean future) {
Query query;
if (now != null) {
query = getSession().getNamedQuery("FutureBundleBean.many.byDateFuture");
query.setTimestamp("now", now);
} else {
query = getSession().getNamedQuery("FutureBundleBean.many.byFuture");
}
query.setParameter("future", future);
return query.list();
}
@Override
public FutureBundleBean nextFutureBundleBean(Date now, FutureSecurityBean future) {
Query query = getSession().getNamedQuery("FutureBundleBean.one.nextBundle");
query.setTimestamp("now", now);
query.setParameter("future", future);
return (FutureBundleBean) query.uniqueResult();
}
@Override
public void persistFutureBundleBeans(final Date now, final FutureSecurityBean future) {
OperationTimer timer = new OperationTimer(s_logger, "persistFutureBundleBeans");
final Set<FutureBundleBean> beanBasket = future.getBasket();
final List<FutureBundleBean> dbBasket = getFutureBundleBeans(now, future);
if (now != null) {
// anything in the database (at this timestamp), but not in the basket must be "terminated" at this timestamp
boolean beansUpdated = false;
for (FutureBundleBean dbBundle : dbBasket) {
if (!beanBasket.contains(dbBundle)) {
dbBundle.setEndDate(now);
getSession().update(dbBundle);
beansUpdated = true;
}
}
if (beansUpdated) {
getSession().flush();
beansUpdated = false;
}
// anything not in the database (at this timestamp), but in the basket must be added:
for (FutureBundleBean beanBundle : beanBasket) {
if (!dbBasket.contains(beanBundle)) {
final FutureBundleBean next = nextFutureBundleBean(now, future);
if (next != null) {
beanBundle.setId(next.getId());
beanBundle.setEndDate(next.getEndDate());
next.setStartDate(now);
getSession().update(next);
} else {
beanBundle.setStartDate(now);
beanBundle.setEndDate(null);
if (beanBundle.getId() != null) {
getSession().update(beanBundle);
} else {
Long id = (Long) getSession().save(beanBundle);
beanBundle.setId(id);
}
}
beansUpdated = true;
}
}
if (beansUpdated) {
getSession().flush();
}
} else {
// anything in the database with any timestamp that isn't null/null must be deleted
// anything in the database, but not in the basket, must be deleted
boolean beansUpdated = false;
for (FutureBundleBean dbBundle : dbBasket) {
if (!beanBasket.contains(dbBundle)) {
getSession().delete(dbBundle);
beansUpdated = true;
} else if ((dbBundle.getStartDate() != null) || (dbBundle.getEndDate() != null)) {
dbBundle.setStartDate(null);
dbBundle.setEndDate(null);
getSession().update(dbBundle);
beansUpdated = true;
}
}
// anything not in the database, but in the basket, must be added (null/null)
for (FutureBundleBean beanBundle : beanBasket) {
if (!dbBasket.contains(beanBundle)) {
beanBundle.setStartDate(null);
beanBundle.setEndDate(null);
if (beanBundle.getId() != null) {
getSession().update(beanBundle);
} else {
Long id = (Long) getSession().save(beanBundle);
beanBundle.setId(id);
}
beansUpdated = true;
}
}
if (beansUpdated) {
getSession().flush();
}
}
timer.finished();
}
//-------------------------------------------------------------------------
/**
* Extracts the security row id.
* @param id the identifier to extract from, not null
* @return the extracted row id
*/
protected long extractRowId(final UniqueId id) {
try {
return Long.parseLong(id.getValue()) + Long.parseLong(id.getVersion());
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("UniqueId is not from this security master: " + id, ex);
}
}
}
| 34.168129 | 140 | 0.692439 |
fdbc51d8b60718c20536ec775f9ce73d5c9f87cb | 18,641 | /*
* =============================================================================
*
* Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.util;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* <p>
* Utility class for obtaining a correct classloader on which to operate from a
* specific class.
* </p>
*
* @author Daniel Fernández
*
* @since 2.0.6
*
*/
public final class ClassLoaderUtils {
private static final ClassLoader classClassLoader;
private static final ClassLoader systemClassLoader;
private static final boolean systemClassLoaderAccessibleFromClassClassLoader;
static {
classClassLoader = getClassClassLoader(ClassLoaderUtils.class);
systemClassLoader = getSystemClassLoader();
systemClassLoaderAccessibleFromClassClassLoader = isKnownClassLoaderAccessibleFrom(systemClassLoader, classClassLoader);
}
/**
* <p>
* Try to obtain a classloader, following these priorities:
* </p>
* <ol>
* <li>If there is a <i>thread context class loader</i>, return it.</li>
* <li>Else if there is a class loader related to the class passed as argument, return it.</li>
* <li>Else return the <i>system class loader</i>.</li>
* </ol>
*
* @param clazz the class which loader will be obtained in the second step. Can be null (that will
* skip that second step).
* @return a non-null, safe classloader to use.
*/
public static ClassLoader getClassLoader(final Class<?> clazz) {
// Context class loader can be null
final ClassLoader contextClassLoader = getThreadContextClassLoader();
if (contextClassLoader != null) {
return contextClassLoader;
}
if (clazz != null) {
// The class loader for a specific class can also be null
final ClassLoader clazzClassLoader = getClassClassLoader(clazz);
if (clazzClassLoader != null) {
return clazzClassLoader;
}
}
// The only class loader we can rely on for not being null is the system one
return systemClassLoader;
}
/**
* <p>
* Obtain a class by name, throwing an exception if it is not present.
* </p>
* <p>
* First the <em>context class loader</em> will be used. If this class loader is not
* able to load the class, then the <em>class class loader</em>
* ({@code ClassLoaderUtils.class.getClassLoader()}) will be used if it is different from
* the thread context one. Last, the System class loader will be tried.
* </p>
* <p>
* This method does never return {@code null}.
* </p>
*
* @param className the name of the class to be obtained.
* @return the loaded class (null never returned).
* @throws ClassNotFoundException if the class could not be loaded.
*
* @since 3.0.3
*
*/
public static Class<?> loadClass(final String className) throws ClassNotFoundException {
ClassNotFoundException notFoundException = null;
// First try the context class loader
final ClassLoader contextClassLoader = getThreadContextClassLoader();
if (contextClassLoader != null) {
try {
return Class.forName(className, false, contextClassLoader);
} catch (final ClassNotFoundException cnfe) {
notFoundException = cnfe;
// Pass-through, there might be other ways of obtaining it
// note anyway that this is not really normal: the context class loader should be
// either able to resolve any of our application's classes, or to delegate to a class
// loader that can do that.
}
}
// The thread context class loader might have already delegated to both the class
// and system class loaders, in which case it makes little sense to query them too.
if (!isKnownLeafClassLoader(contextClassLoader)) {
// The context class loader didn't help, so... maybe the class one?
if (classClassLoader != null && classClassLoader != contextClassLoader) {
try {
return Class.forName(className, false, classClassLoader);
} catch (final ClassNotFoundException cnfe) {
if (notFoundException == null) {
notFoundException = cnfe;
}
// Pass-through, maybe the system class loader can do it? - though it would be *really* weird...
}
}
if (!systemClassLoaderAccessibleFromClassClassLoader) {
// The only class loader we can rely on for not being null is the system one
if (systemClassLoader != null && systemClassLoader != contextClassLoader && systemClassLoader != classClassLoader) {
try {
return Class.forName(className, false, systemClassLoader);
} catch (final ClassNotFoundException cnfe) {
if (notFoundException == null) {
notFoundException = cnfe;
}
// Pass-through, anyway we have a return null after this...
}
}
}
}
// If we have to throw an exception, we will do so with the highest-level one just in case it provides
// a useful message. So preferably we will throw the one coming from the thread context class loader,
// if not then the class class loader, etc.
throw notFoundException;
}
/**
* <p>
* Try to obtain a class by name, returning {@code null} if not found.
* </p>
* <p>
* This method works very similarly to {@link #loadClass(String)} but will just return {@code null}
* if the class is not found by the sequence of class loaders being tried.
* </p>
*
* @param className the name of the class to be obtained.
* @return the found class, or {@code null} if it could not be found.
*
* @since 3.0.3
*
*/
public static Class<?> findClass(final String className) {
try {
return loadClass(className);
} catch (final ClassNotFoundException cnfe) {
// ignored, we will just return null in this case
return null;
}
}
/**
* <p>
* Checks whether a class is present at the application's class path.
* </p>
* <p>
* This method works very similarly to {@link #findClass(String)} but will just return {@code true}
* or {@code false} depending on whether the class could be found or not.
* </p>
*
* @param className the name of the class to be checked.
* @return {@code true} if the class was found (by any class loader), {@code false} if not.
*
* @since 3.0.3
*
*/
public static boolean isClassPresent(final String className) {
return findClass(className) != null;
}
/**
* <p>
* Try to obtain a resource by name, returning {@code null} if it could not be located.
* </p>
* <p>
* First the <em>context class loader</em> will be used. If this class loader is not
* able to locate the resource, then the <em>class class loader</em>
* ({@code ClassLoaderUtils.class.getClassLoader()}) will be used if it is different from
* the thread context one. Last, the System class loader will be tried.
* </p>
*
* @param resourceName the name of the resource to be obtained.
* @return the found resource, or {@code null} if it could not be located.
*
* @since 3.0.3
*
*/
public static URL findResource(final String resourceName) {
// First try the context class loader
final ClassLoader contextClassLoader = getThreadContextClassLoader();
if (contextClassLoader != null) {
final URL url = contextClassLoader.getResource(resourceName);
if (url != null) {
return url;
}
// Pass-through, there might be other ways of obtaining it
// note anyway that this is not really normal: the context class loader should be
// either able to resolve any of our application's resources, or to delegate to a class
// loader that can do that.
}
// The thread context class loader might have already delegated to both the class
// and system class loaders, in which case it makes little sense to query them too.
if (!isKnownLeafClassLoader(contextClassLoader)) {
// The context class loader didn't help, so... maybe the class one?
if (classClassLoader != null && classClassLoader != contextClassLoader) {
final URL url = classClassLoader.getResource(resourceName);
if (url != null) {
return url;
}
// Pass-through, maybe the system class loader can do it? - though it would be *really* weird...
}
if (!systemClassLoaderAccessibleFromClassClassLoader) {
// The only class loader we can rely on for not being null is the system one
if (systemClassLoader != null && systemClassLoader != contextClassLoader && systemClassLoader != classClassLoader) {
final URL url = systemClassLoader.getResource(resourceName);
if (url != null) {
return url;
}
// Pass-through, anyway we have a return null after this...
}
}
}
return null;
}
/**
* <p>
* Checks whether a resource is present at the application's class path.
* </p>
* <p>
* This method works very similarly to {@link #findResource(String)} but will just return {@code true}
* or {@code false} depending on whether the resource could be located or not.
* </p>
*
* @param resourceName the name of the resource to be checked.
* @return {@code true} if the class was located (by any class loader), {@code false} if not.
*
* @since 3.0.3
*
*/
public static boolean isResourcePresent(final String resourceName) {
return findResource(resourceName) != null;
}
/**
* <p>
* Obtain a resource by name, throwing an exception if it is not present.
* </p>
* <p>
* First the <em>context class loader</em> will be used. If this class loader is not
* able to locate the resource, then the <em>class class loader</em>
* ({@code ClassLoaderUtils.class.getClassLoader()}) will be used if it is different from
* the thread context one. Last, the System class loader will be tried.
* </p>
* <p>
* This method does never return {@code null}.
* </p>
*
* @param resourceName the name of the resource to be obtained.
* @return an input stream on the resource (null never returned).
* @throws IOException if the resource could not be located.
*
* @since 3.0.3
*
*/
public static InputStream loadResourceAsStream(final String resourceName) throws IOException {
final InputStream inputStream = findResourceAsStream(resourceName);
if (inputStream != null) {
return inputStream;
}
// No way to obtain that resource, so we must raise an IOException
throw new IOException("Could not locate resource '" + resourceName + "' in the application's class path");
}
/**
* <p>
* Try to obtain a resource by name, returning {@code null} if it could not be located.
* </p>
* <p>
* This method works very similarly to {@link #loadResourceAsStream(String)} but will just return {@code null}
* if the resource cannot be located by the sequence of class loaders being tried.
* </p>
*
* @param resourceName the name of the resource to be obtained.
* @return an input stream on the resource, or {@code null} if it could not be located.
*
* @since 3.0.3
*
*/
public static InputStream findResourceAsStream(final String resourceName) {
// First try the context class loader
final ClassLoader contextClassLoader = getThreadContextClassLoader();
if (contextClassLoader != null) {
final InputStream inputStream = contextClassLoader.getResourceAsStream(resourceName);
if (inputStream != null) {
return inputStream;
}
// Pass-through, there might be other ways of obtaining it
// note anyway that this is not really normal: the context class loader should be
// either able to resolve any of our application's resources, or to delegate to a class
// loader that can do that.
}
// The thread context class loader might have already delegated to both the class
// and system class loaders, in which case it makes little sense to query them too.
if (!isKnownLeafClassLoader(contextClassLoader)) {
// The context class loader didn't help, so... maybe the class one?
if (classClassLoader != null && classClassLoader != contextClassLoader) {
final InputStream inputStream = classClassLoader.getResourceAsStream(resourceName);
if (inputStream != null) {
return inputStream;
}
// Pass-through, maybe the system class loader can do it? - though it would be *really* weird...
}
if (!systemClassLoaderAccessibleFromClassClassLoader) {
// The only class loader we can rely on for not being null is the system one
if (systemClassLoader != null && systemClassLoader != contextClassLoader && systemClassLoader != classClassLoader) {
final InputStream inputStream = systemClassLoader.getResourceAsStream(resourceName);
if (inputStream != null) {
return inputStream;
}
// Pass-through, anyway we have a return null after this...
}
}
}
return null;
}
/*
* This will return the thread context class loader if it is possible to access it
* (depending on security restrictions)
*/
private static ClassLoader getThreadContextClassLoader() {
try {
return Thread.currentThread().getContextClassLoader();
} catch (final SecurityException se) {
// The SecurityManager prevents us from accessing, so just ignore it
return null;
}
}
/*
* This will return the class class loader if it is possible to access it
* (depending on security restrictions)
*/
private static ClassLoader getClassClassLoader(final Class<?> clazz) {
try {
return clazz.getClassLoader();
} catch (final SecurityException se) {
// The SecurityManager prevents us from accessing, so just ignore it
return null;
}
}
/*
* This will return the system class loader if it is possible to access it
* (depending on security restrictions)
*/
private static ClassLoader getSystemClassLoader() {
try {
return ClassLoader.getSystemClassLoader();
} catch (final SecurityException se) {
// The SecurityManager prevents us from accessing, so just ignore it
return null;
}
}
/*
* This method determines whether it is known that a this class loader is a a child of another one, or equal to it.
* The "known" part is because SecurityManager could be preventing us from knowing such information.
*/
private static boolean isKnownClassLoaderAccessibleFrom(final ClassLoader accessibleCL, final ClassLoader fromCL) {
if (fromCL == null) {
return false;
}
ClassLoader parent = fromCL;
try {
while (parent != null && parent != accessibleCL) {
parent = parent.getParent();
}
return (parent != null && parent == accessibleCL);
} catch (final SecurityException se) {
// The SecurityManager prevents us from accessing, so just ignore it
return false;
}
}
/*
* This method determines whether it is known that a this class loader is a "leaf", in the sense that
* going up through its hierarchy we are able to find both the class class loader and the system class
* loader. This is used for determining whether we should be confident on the thread-context class loader
* delegation mechanism or rather try to perform class/resource resolution manually on the other class loaders.
*/
private static boolean isKnownLeafClassLoader(final ClassLoader classLoader) {
if (classLoader == null) {
return false;
}
if (!isKnownClassLoaderAccessibleFrom(classClassLoader, classLoader)) {
// We cannot access the class class loader from the specified class loader, so this is not a leaf
return false;
}
// Now we know there is a way to reach the class class loader from the argument class loader, so we should
// base or results on whether there is a way to reach the system class loader from the class class loader.
return systemClassLoaderAccessibleFromClassClassLoader;
}
private ClassLoaderUtils() {
super();
}
}
| 37.059642 | 132 | 0.604689 |
b71f955d226a41ab91c19cc542d2a630234f9693 | 1,339 | package io.mangoo.i18n;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.util.Locale;
import org.junit.Test;
import io.mangoo.core.Application;
import io.mangoo.enums.Validation;
/**
*
* @author svenkubiak
*
*/
public class MessagesTest {
@Test
public void testReload() {
//given
Messages messages = Application.getInstance(Messages.class);
messages.reload(Locale.GERMAN);
//then
assertThat(messages.get("welcome"), equalTo("willkommen"));
//when
messages.reload(Locale.ENGLISH);
//then
assertThat(messages.get("welcome"), equalTo("welcome"));
}
@Test
public void testGet() {
//given
Messages messages = Application.getInstance(Messages.class);
//when
messages.reload(Locale.GERMAN);
//then
assertThat(messages.get("welcome"), equalTo("willkommen"));
}
@Test
public void testGetWithKey() {
//given
Messages messages = Application.getInstance(Messages.class);
messages.reload(Locale.ENGLISH);
//then
assertThat(messages.get(Validation.EMAIL_KEY.name(), "foo"), equalTo("foo must be a valid eMail address"));
}
}
| 23.086207 | 115 | 0.613891 |
1369a4ad53e9b1641382d3f419902a79f68d5310 | 696 | package de.dkweb.crillionic.utils;
import de.dkweb.crillionic.model.GameWorld;
/**
* Created by dirkweber
*/
public class PhysicsUpdater {
private final static float PHYSICS_UPDATE_RATE_PER_SECOND = 1/60f;
private float elapsedRenderTime;
private GameWorld gameWorld;
public PhysicsUpdater(GameWorld gameWorld) {
this.gameWorld = gameWorld;
}
public void doPhysics(float renderTimeDelta) {
elapsedRenderTime += renderTimeDelta;
while (elapsedRenderTime >= PHYSICS_UPDATE_RATE_PER_SECOND) {
gameWorld.getPhysicsWorld().step(PHYSICS_UPDATE_RATE_PER_SECOND, 6, 2);
elapsedRenderTime -= renderTimeDelta;
}
}
}
| 27.84 | 83 | 0.711207 |
63b5423a576d3f6b452899c0cdebb547a2c4a3e1 | 8,015 | /**
* 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 com.huawei.streaming;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.huawei.streaming.event.Attribute;
import com.huawei.streaming.event.EventTypeMng;
import com.huawei.streaming.event.TupleEvent;
import com.huawei.streaming.event.TupleEventType;
import com.huawei.streaming.exception.StreamingException;
import com.huawei.streaming.expression.ConstExpression;
import com.huawei.streaming.expression.IExpression;
import com.huawei.streaming.expression.PreviousExpression;
import com.huawei.streaming.expression.PropertyValueExpression;
import com.huawei.streaming.output.OutPutPrint;
import com.huawei.streaming.output.OutputType;
import com.huawei.streaming.process.SelectSubProcess;
import com.huawei.streaming.processor.SimpleOutputProcessor;
import com.huawei.streaming.support.SupportConst;
import com.huawei.streaming.view.FirstLevelStream;
import com.huawei.streaming.view.ProcessView;
import com.huawei.streaming.window.LengthBatchWindow;
import com.huawei.streaming.window.LengthSlideWindow;
import com.huawei.streaming.window.RandomAccessByIndexService;
import com.huawei.streaming.window.RelativeAccessByEventAndIndexService;
import com.huawei.streaming.window.WindowRandomAccess;
import com.huawei.streaming.window.WindowRelativeAccess;
/**
* <PreviousTest>
* <功能详细描述>
*
*/
public class PreviousTest
{
/**
* <test()>
* <功能详细描述>
*/
@Test
public void test()
throws StreamingException
{
//select prev(1, a) from schemName.WinLengthSlide(5);
EventTypeMng eventTypeMng = new EventTypeMng();
//输入流类型
List<Attribute> schema = new ArrayList<Attribute>();
Attribute attributeA = new Attribute(Integer.class, "a");
Attribute attributeB = new Attribute(Integer.class, "b");
Attribute attributeC = new Attribute(String.class, "c");
schema.add(attributeA);
schema.add(attributeB);
schema.add(attributeC);
TupleEventType tupleEventType = new TupleEventType("schemName", schema);
//输出流类型
List<Attribute> outschema = new ArrayList<Attribute>();
Attribute attributePrev = new Attribute(Integer.class, "prev(1, a)");
outschema.add(attributePrev);
TupleEventType outtupleEventType = new TupleEventType("outschema", outschema);
eventTypeMng.addEventType(tupleEventType);
eventTypeMng.addEventType(outtupleEventType);
FirstLevelStream firststream = new FirstLevelStream();
LengthSlideWindow win = new LengthSlideWindow(SupportConst.I_FIVE);
ProcessView processview = new ProcessView();
/**
* select
*/
IExpression[] exprNodes = new IExpression[SupportConst.I_ONE];
exprNodes[0] = new PreviousExpression(new ConstExpression(1), new PropertyValueExpression("a", Integer.class));
/**
* DataCollection
*/
RandomAccessByIndexService service = new RandomAccessByIndexService();
WindowRandomAccess randomAccess = new WindowRandomAccess(service);
win.setDataCollection(randomAccess);
((PreviousExpression)exprNodes[0]).setService(service);
SelectSubProcess selector = new SelectSubProcess("out", exprNodes, null, outtupleEventType);
SimpleOutputProcessor simple = new SimpleOutputProcessor(selector, null, new OutPutPrint(), OutputType.I);
firststream.addView(win);
win.addView(processview);
processview.setProcessor(simple);
firststream.start();
Map<String, Object> values = new HashMap<String, Object>();
//发送数据
long startTime = System.currentTimeMillis();
for (int i = 0; i < SupportConst.I_FIVE; i++)
{
values.put("a", i);
values.put("b", i);
values.put("c", "abc");
TupleEvent tupleEvent2 = new TupleEvent("stream", "schemName", values, eventTypeMng);
firststream.add(tupleEvent2);
}
long endTime = System.currentTimeMillis();
firststream.stop();
System.out.println(endTime - startTime);
}
/**
* <test()>
* <功能详细描述>
*/
@Test
public void testBatchWindow()
throws StreamingException
{
//select prev(1, a) from schemName.WinLengthBatch(5);
EventTypeMng eventTypeMng = new EventTypeMng();
//输入流类型
List<Attribute> schema = new ArrayList<Attribute>();
Attribute attributeA = new Attribute(Integer.class, "a");
Attribute attributeB = new Attribute(Integer.class, "b");
Attribute attributeC = new Attribute(String.class, "c");
schema.add(attributeA);
schema.add(attributeB);
schema.add(attributeC);
TupleEventType tupleEventType = new TupleEventType("schemName", schema);
//输出流类型
List<Attribute> outschema = new ArrayList<Attribute>();
Attribute attributePrev = new Attribute(Integer.class, "prev(1, a)");
outschema.add(attributePrev);
TupleEventType outtupleEventType = new TupleEventType("outschema", outschema);
eventTypeMng.addEventType(tupleEventType);
eventTypeMng.addEventType(outtupleEventType);
FirstLevelStream firststream = new FirstLevelStream();
LengthBatchWindow win = new LengthBatchWindow(SupportConst.I_FIVE);
ProcessView processview = new ProcessView();
/**
* select
*/
IExpression[] exprNodes = new IExpression[SupportConst.I_ONE];
exprNodes[0] = new PreviousExpression(new ConstExpression(1), new PropertyValueExpression("a", Integer.class));
/**
* DataCollection
*/
RelativeAccessByEventAndIndexService service = new RelativeAccessByEventAndIndexService();
WindowRelativeAccess relativeAccess = new WindowRelativeAccess(service);
win.setDataCollection(relativeAccess);
((PreviousExpression)exprNodes[0]).setService(service);
SelectSubProcess selector = new SelectSubProcess("out", exprNodes, null, outtupleEventType);
SimpleOutputProcessor simple = new SimpleOutputProcessor(selector, null, new OutPutPrint(), OutputType.I);
firststream.addView(win);
win.addView(processview);
processview.setProcessor(simple);
firststream.start();
Map<String, Object> values = new HashMap<String, Object>();
//发送数据
long startTime = System.currentTimeMillis();
for (int i = 0; i < SupportConst.I_FIVE; i++)
{
values.put("a", i);
values.put("b", i);
values.put("c", "abc");
TupleEvent tupleEvent2 = new TupleEvent("stream", "schemName", values, eventTypeMng);
firststream.add(tupleEvent2);
}
long endTime = System.currentTimeMillis();
firststream.stop();
System.out.println(endTime - startTime);
}
}
| 38.166667 | 119 | 0.669744 |
a56755588847dc3d11be3d5be55a68350699838e | 3,420 | package example.plugins;
import example.vo.Page;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import static org.apache.ibatis.reflection.SystemMetaObject.DEFAULT_OBJECT_FACTORY;
import static org.apache.ibatis.reflection.SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY;
/**
* Created by gongpu on 2019/9/25 9:58
*/
@Intercepts(@Signature(type = StatementHandler.class,method = "prepare",args = {Connection.class, Integer.class}))
public class MyPagePlugin implements Interceptor{
String databaseType=null;
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
MetaObject metaObject = MetaObject.forObject(statementHandler,DEFAULT_OBJECT_FACTORY,
DEFAULT_OBJECT_WRAPPER_FACTORY,new DefaultReflectorFactory());
String sqlId = (String) metaObject.getValue("delegate.mappedStatement.id");
if (isPageSql(sqlId)){
String sql = statementHandler.getBoundSql().getSql();
String countSql="select count(0) as countD from ("+sql+") AS a";
Connection connection = (Connection) invocation.getArgs()[0];
PreparedStatement preparedStatement = connection.prepareStatement(countSql);
ParameterHandler parameterHandler = statementHandler.getParameterHandler();
/**
* 替换实参
*/
parameterHandler.setParameters(preparedStatement);
ResultSet resultSet = preparedStatement.executeQuery();
int count=0;
if (resultSet.next()){
count=resultSet.getInt(1);
}
resultSet.close();
preparedStatement.close();
Map<String,Object> parameterObject = (Map<String, Object>) parameterHandler.getParameterObject();
Page page = (Page) parameterObject.get("page");
page.setCount(count);
String pageSql = getPageSql(sql, page);
metaObject.setValue("delegate.boundSql.sql",pageSql);
}
return invocation.proceed();
}
private boolean isPageSql(String sqlId) {
String regex=".*ByPage$";
boolean matches = Pattern.matches(regex, sqlId);
return matches;
}
public String getPageSql(String sql,Page page){
if(databaseType.equals("mysql")){
return sql +" limit "+page.getPageIndex()+","+page.getPageIndex()*page.getPageSize();
}else if(databaseType.equals("oracle")){
//拼接oracle的分语句
}
return sql+" limit "+page.getPageIndex()+","+page.getPageIndex()*page.getPageSize();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target,this);
}
@Override
public void setProperties(Properties properties) {
String sqlType = properties.getProperty("sqlType");
this.databaseType=sqlType;
System.out.println(sqlType);
}
}
| 37.582418 | 114 | 0.682164 |
9cf7a4bacc2d3ad17c64a7fad073eeaa5150b3c8 | 681 | //
// Decompiled by Procyon v0.5.36
//
package org.mudebug.prapr.reloc.commons.httpclient;
public class Header extends NameValuePair
{
public Header() {
this(null, null);
}
public Header(final String name, final String value) {
super(name, value);
}
public String toExternalForm() {
return ((null == this.getName()) ? "" : this.getName()) + ": " + ((null == this.getValue()) ? "" : this.getValue()) + "\r\n";
}
public String toString() {
return this.toExternalForm();
}
public HeaderElement[] getValues() throws HttpException {
return HeaderElement.parse(this.getValue());
}
}
| 23.482759 | 133 | 0.58884 |
8b1d70977973831233bc28947214a7bee94e60df | 3,145 | /*
*
* Copyright (C) 2020 iQIYI (www.iqiyi.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.qiyi.lens.utils.reflect;
import com.qiyi.lens.utils.iface.IViewInfoHandle;
import com.qiyi.lens.utils.iface.ObjectDescription;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class CollectionFailFetcher {
private Object value;
public CollectionFailFetcher(Object value) {
this.value = value;
}
public Object[] getObjectSizeAndIndexAt(IViewInfoHandle handle, Object view, int size, int index) {
Class cls = value.getClass();
List data = new LinkedList();
while (cls != Object.class && cls != null) {
Field[] flds = cls.getDeclaredFields();
for (Field field : flds) {
try {
field.setAccessible(true);
Object object = field.get(value);
if (object instanceof List) {
List list = (List) object;
if (list.size() == size) {
Object indexValue = list.get(index);
data.add(indexValue);
if (handle != null) {
Object[] vars = handle.onViewAnalyse(view, indexValue);
if (vars != null) {
Collections.addAll(data, vars);
}
}
}
} else if (object instanceof Object[]) {
Object[] array = (Object[]) object;
if (array.length == size) {
data.add(new ObjectDescription(array[index],"index " + index));
if (handle != null) {
Object[] vars = handle.onViewAnalyse(view, array[index]);
if (vars != null) {
data.addAll(Arrays.asList(vars));
}
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
cls = cls.getSuperclass();
}
if (!data.isEmpty()) {
Object[] value = new Object[data.size()];
data.toArray(value);
return value;
}
return null;
}
}
| 32.42268 | 103 | 0.498569 |
94e22928792ebaecfe38a5129d8737267487bf3e | 487 | package com.voxelwind.server.network.mcpe.packets;
import com.voxelwind.nbt.util.Varints;
import com.voxelwind.server.network.NetworkPackage;
import io.netty.buffer.ByteBuf;
import lombok.Data;
@Data
public class McpeSetPlayerGameType implements NetworkPackage
{
private int gamemode;
@Override
public void decode (ByteBuf buffer)
{
gamemode = Varints.decodeSigned (buffer);
}
@Override
public void encode (ByteBuf buffer)
{
Varints.encodeSigned (buffer, gamemode);
}
}
| 19.48 | 60 | 0.780287 |
a43551cad802a31e6f0e506560c1eb7812a5add2 | 13,347 | /*
* Copyright (c) 2002 World Wide Web Consortium,
* (Massachusetts Institute of Technology, Institut National de
* Recherche en Informatique et en Automatique, Keio University). All
* Rights Reserved. This program is distributed under the W3C's Software
* Intellectual Property License. This program is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE.
* See W3C License http://www.w3.org/Consortium/Legal/ for more details.
*/
package org.w3c.dom.xpath;
import org.w3c.dom.Node;
import org.w3c.dom.DOMException;
/**
* <strong>DOM Level 3 WD Experimental:
* The DOM Level 3 specification is at the stage
* of Working Draft, which represents work in
* progress and thus may be updated, replaced,
* or obsoleted by other documents at any time.</strong> <p>
* <code>XPathEvaluator</code>, which will provide evaluation of XPath 1.0
* expressions with no specialized extension functions or variables. It is
* expected that the <code>XPathEvaluator</code> interface will be
* implemented on the same object which implements the <code>Document</code>
* interface in an implementation which supports the XPath DOM module.
* <code>XPathEvaluator</code> implementations may be available from other
* sources that may provide support for special extension functions or
* variables which are not defined in this specification. The methods of
* XPathExpression should be named with more-XPath- specific names because
* the interface will often be implemented by the same object which
* implements document.No change.The point of interfaces is to localize the
* implementing namespace. This would make the method names unnecessarily
* long and complex even though there are no conflicts in the interface
* itself. The new core method getInterface is designed for discovering
* interfaces of additional modules that may not be directly implemented on
* the objects to which they are attached. This could be used to implement
* XPath on a separate object. The user only refers to the separate
* interfaces and not the proprietary aggregate implementation.Should entity
* refs be supported so that queries can be made on them?No change.We will
* not do this now. They are not part of the XPath data model. Note that
* they may be present in the hierarchy of returned nodes, but may not
* directly be requested or returned in the node set.What does createResult
* create when one wants to reuse the XPath?It is not useful.Removed method.
* Should ordering be a separate flag, or a type of result that can be
* requested. As a type of result, it can be better optimized in
* implementations.It makes sense as a type of result. Changed.Removed
* method.Implementing XPathEvaluator on Document can be a problem due to
* conflicts in the names of the methods.The working group finds no better
* solution. GetInterface in Level 3 permits the object to be implemented
* separately. We should be committed to this. We will leave this issue open
* to see if we get more feedback on it.How does this interface adapt to
* XPath 2.0 and other query languages.No change.This interface is not
* intended to adapt to XPath 2.0 or other languages. The models of these
* are likely to be incompatible enough to require new APIs.For alternate
* implementations that can use this API, it can be obtained from different
* sources.Support for custom variables and functions would be very useful.
* No change.It is possible for an implementation to supply alternative
* sources of an XPathEvaluator that can be customized with a custom
* variable and function context. We do not specify how this is
* accomplished. It is too complex to address in this version of the XPath
* DOM.
* <p>See also the <a href='http://www.w3.org/TR/2002/WD-DOM-Level-3-XPath-20020328'>Document Object Model (DOM) Level 3 XPath Specification</a>.
*/
public interface XPathEvaluator {
/**
* Creates a parsed XPath expression with resolved namespaces. This is
* useful when an expression will be reused in an application since it
* makes it possible to compile the expression string into a more
* efficient internal form and preresolve all namespace prefixes which
* occur within the expression.createExpression should not raise
* exceptions about type coercion.This was already fixed in the public
* draft.
* @param expression The XPath expression string to be parsed.
* @param resolver The <code>resolver</code> permits translation of
* prefixes within the XPath expression into appropriate namespace URIs
* . If this is specified as <code>null</code>, any namespace prefix
* within the expression will result in <code>DOMException</code>
* being thrown with the code <code>NAMESPACE_ERR</code>.
* @return The compiled form of the XPath expression.
* @exception XPathException
* INVALID_EXPRESSION_ERR: Raised if the expression is not legal
* according to the rules of the <code>XPathEvaluator</code>i
* @exception DOMException
* NAMESPACE_ERR: Raised if the expression contains namespace prefixes
* which cannot be resolved by the specified
* <code>XPathNSResolver</code>.
*/
public XPathExpression createExpression(String expression,
XPathNSResolver resolver)
throws XPathException, DOMException;
/**
* Adapts any DOM node to resolve namespaces so that an XPath expression
* can be easily evaluated relative to the context of the node where it
* appeared within the document. This adapter works by calling the
* method <code>lookupNamespacePrefix</code> on <code>Node</code>.It
* should be possible to create an XPathNSResolver that does not rely on
* a node, but which implements a map of resolutions that can be added
* to by the application.No change.The application can easily create
* this, which was why the interface was designed as it is. The
* specification will not require a specific factory at this time for
* application populated maps.There should be type restrictions on which
* types of nodes may be adapted by createNSResolver.No change.The
* namespace methods on the Node interface of the Level 3 core may be
* called without exception on all node types. In some cases no non-null
* namespace resolution will ever be returned. That is what may also be
* expected of this adapter.
* @param nodeResolver The node to be used as a context for namespace
* resolution.
* @return <code>XPathNSResolver</code> which resolves namespaces with
* respect to the definitions in scope for a specified node.
*/
public XPathNSResolver createNSResolver(Node nodeResolver);
/**
* Evaluates an XPath expression string and returns a result of the
* specified type if possible.An exception needs to be raised when an
* XPath expression is evaluated on a node such as an EntityReference
* which cannot serve as an XPath context node.Done: NOT_SUPPORTED_ERR.A
* description is needed of what happens when the node passed to the
* evaluation function is a Text or CDATASection in the DOM case where
* the text may be fragmented between text nodes.Done.Eliminate the
* evaluate method from XPathEvaluator, forcing everyone to create
* expressions.No change.Any implementor can easily implement it by
* creating an expression. Having it available as a separate routine is
* a convenience and may be an optimization as well in some cases.Revert
* to multiple evaluateAs methods instead of passing a type code.No
* change.This is an alternative which eliminates a method argument
* while adding methods, but the type code is used to designate the type
* on returns anyway and using it as an argument to specify any coercion
* seems natural to many.Error exceptions are needed when there is a
* mismatch between the implementation of XPathEvaluator and the context
* node being evaluated.Done: WRONG_DOCUMENT_ERRConcern that the XPath
* API should only support natural results of XPath expression, without
* convenience coercion or alternative representations. Any special
* thing such as ordering should be added later to resultNo change.We
* have significant use cases for returning alternative types and
* representations by explicit request in advance.Eliminate the reusable
* result argument.No change.No. We have use cases for it, and there is
* already an implementation showing there is nothing wrong with it.
* State that the XPathNSResolver argument may be a function in
* Javascript.Yes.There is an exception when there is a problem parsing
* the expression, but none when there is a problem evaluating the
* expression.No change.If the expression parsing was OK, then the worst
* that can happen is an empty result is returned.When requesting any
* type, the implementation should be permitted to return any type of
* node set, i.e. ordered or unordered, it finds convenient.No change.
* The iterator it returns may contain ordered results, but identifying
* it as such produces undesirable results, because it would create
* complexity for the user -- requiring checking two types to see if the
* result was a node set -- or incompatibility caused by assuming it was
* always the one returned by a particular implementation the developer
* was using.NAMESPACE_ERR description is not appropriate to the way it
* is being used here.Make the description of NAMESPACE_ERR in the core
* specification more general.Should the INVALID_EXPRESSION_ERR be
* INVALID_SYNTAX_ERR?No change.We can improve the description of the
* error, but the name is appropriate as-is. It covers not only syntax
* errors but expression errors, such as when the implementation has no
* custom functions or variables but the expression specifies custom
* functions or variables.
* @param expression The XPath expression string to be parsed and
* evaluated.
* @param contextNode The <code>context</code> is context node for the
* evaluation of this XPath expression. If the XPathEvaluator was
* obtained by casting the <code>Document</code> then this must be
* owned by the same document and must be a <code>Document</code>,
* <code>Element</code>, <code>Attribute</code>, <code>Text</code>,
* <code>CDATASection</code>, <code>Comment</code>,
* <code>ProcessingInstruction</code>, or <code>XPathNamespace</code>
* node. If the context node is a <code>Text</code> or a
* <code>CDATASection</code>, then the context is interpreted as the
* whole logical text node as seen by XPath, unless the node is empty
* in which case it may not serve as the XPath context.
* @param resolver The <code>resolver</code> permits translation of
* prefixes within the XPath expression into appropriate namespace URIs
* . If this is specified as <code>null</code>, any namespace prefix
* within the expression will result in <code>DOMException</code>
* being thrown with the code <code>NAMESPACE_ERR</code>.
* @param type If a specific <code>type</code> is specified, then the
* result will be coerced to return the specified type relying on
* XPath type conversions and fail if the desired coercion is not
* possible. This must be one of the type codes of
* <code>XPathResult</code>.
* @param result The <code>result</code> specifies a specific
* <code>XPathResult</code> which may be reused and returned by this
* method. If this is specified as <code>null</code>or the
* implementation cannot reuse the specified result, a new
* <code>XPathResult</code> will be constructed and returned.
* @return The result of the evaluation of the XPath expression.
* @exception XPathException
* INVALID_EXPRESSION_ERR: Raised if the expression is not legal
* according to the rules of the <code>XPathEvaluator</code>i
* <br>TYPE_ERR: Raised if the result cannot be converted to return the
* specified type.
* @exception DOMException
* NAMESPACE_ERR: Raised if the expression contains namespace prefixes
* which cannot be resolved by the specified
* <code>XPathNSResolver</code>.
* <br>WRONG_DOCUMENT_ERR: The Node is from a document that is not
* supported by this XPathEvaluator.
* <br>NOT_SUPPORTED_ERR: The Node is not a type permitted as an XPath
* context node.
*/
public Object evaluate(String expression,
Node contextNode,
XPathNSResolver resolver,
short type,
Object result)
throws XPathException, DOMException;
}
| 62.07907 | 145 | 0.717614 |
0ad1e7e60a1a3ee5e23ea2dd149fc9687a03ea4b | 682 | package epicsquid.roots.spell.modules;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import java.util.function.Supplier;
public class SpellModule {
private Supplier<ItemStack> ingredient;
private String name;
private TextFormatting colour;
public SpellModule(String name, Supplier<ItemStack> ingredient, TextFormatting colour) {
this.name = name;
this.ingredient = ingredient;
this.colour = colour;
}
public String getName() {
return name;
}
public ItemStack getIngredient() {
return ingredient.get();
}
public TextFormatting getFormat() {
return colour;
}
}
| 21.3125 | 91 | 0.699413 |
bc2a26137fb9a64e13e389c3afd05f16acd6d890 | 3,734 | /*
* Copyright (c) 2016. Guaidaodl
*
* 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.github.guaidaodl.pomodorotimer.ui.statistics;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.google.common.collect.ImmutableListMultimap;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.github.guaidaodl.pomodorotimer.R;
import io.github.guaidaodl.pomodorotimer.data.realm.Tomato;
import io.github.guaidaodl.pomodorotimer.ui.widget.LineView;
import io.github.guaidaodl.pomodorotimer.utils.DateUtils;
import static com.google.common.base.Preconditions.checkNotNull;
public class StatisticsFragment extends Fragment implements StatisticsContract.View {
@BindView(R.id.statistic_day_count)
TextView mDayCountTextView;
@BindView(R.id.statistic_week_count)
TextView mWeekCountTextView;
@BindView(R.id.statistic_month_count)
TextView mMonthCountTextView;
@BindView(R.id.statistic_line_View)
LineView mLineView;
private StatisticsContract.Presenter mPresenter;
public static StatisticsFragment newInstance() {
return new StatisticsFragment();
}
public StatisticsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_statistics, container, false);
ButterKnife.bind(this, rootView);
return rootView;
}
@Override
public void onResume() {
super.onResume();
mPresenter.subscribe();
}
@Override
public void onPause() {
super.onPause();
mPresenter.unSubscribe();
}
//<editor-fold desc="Implementation of StatisticsContract.View">
@Override
public void setPresenter(@NonNull StatisticsContract.Presenter presenter) {
mPresenter = checkNotNull(presenter);
}
@Override
public void showTodayTomatoCount(int tomatoCount) {
mDayCountTextView.setText(String.valueOf(tomatoCount));
}
@Override
public void showWeekTomatoCount(int count) {
mWeekCountTextView.setText(String.valueOf(count));
}
@Override
public void showMonthTomatoCount(int count) {
mMonthCountTextView.setText(String.valueOf(count));
}
@Override
public void showLastSevenDaysTomatoStatistics(@NonNull ImmutableListMultimap<Long, Tomato> statistic) {
checkNotNull(statistic);
int []data = new int[7];
long time = DateUtils.getTodayStartCalendar().getTimeInMillis();
for (int i = 6; i >= 0; i--) {
if (statistic.containsKey(time)) {
data[i] = statistic.get(time).size();
} else {
data[i] = 0;
}
time -= 24 * 60 * 60 * 1000;
}
mLineView.setData(data);
}
@Override
public boolean isActive() {
return isAdded();
}
//</editor-fold>
}
| 28.503817 | 107 | 0.693358 |
23a4f56e7d4d9990fa5cfd02ccefa38661929351 | 3,225 | /*
* Copyright (c) 2005 - 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.wso2.siddhi.core.event.stream.populater;
import org.wso2.siddhi.core.event.stream.MetaStreamEvent;
import org.wso2.siddhi.core.exception.ExecutionPlanCreationException;
import org.wso2.siddhi.query.api.definition.Attribute;
import java.util.ArrayList;
import java.util.List;
import static org.wso2.siddhi.core.util.SiddhiConstants.*;
/**
* The StateEventPopulaterFactory that populates StreamEventPopulater according to MetaStreamEvent and to be mapped attributes
*/
public class StreamEventPopulaterFactory {
/**
* Constructs StreamEventPopulater according to MetaStateEvent and to be mapped attributes
*
* @param metaStreamEvent info for populating the StreamEvent
* @param streamEventChainIndex
* @return StateEventPopulater
*/
public static StreamEventPopulater constructEventPopulator(MetaStreamEvent metaStreamEvent, int streamEventChainIndex, List<Attribute> attributes) {
List<StreamMappingElement> streamMappingElements = new ArrayList<StreamMappingElement>();
for (int i = 0, attributesSize = attributes.size(); i < attributesSize; i++) {
Attribute attribute = attributes.get(i);
StreamMappingElement streamMappingElement = new StreamMappingElement();
streamMappingElement.setFromPosition(i);
int index = metaStreamEvent.getOutputData().indexOf(attribute);
if (index > -1) {
streamMappingElement.setToPosition(new int[]{streamEventChainIndex, 0, OUTPUT_DATA_INDEX, index});
} else {
index = metaStreamEvent.getOnAfterWindowData().indexOf(attribute);
if (index > -1) {
streamMappingElement = new StreamMappingElement();
streamMappingElement.setToPosition(new int[]{streamEventChainIndex, 0, ON_AFTER_WINDOW_DATA_INDEX, index});
} else {
index = metaStreamEvent.getBeforeWindowData().indexOf(attribute);
if (index > -1) {
streamMappingElement = new StreamMappingElement();
streamMappingElement.setToPosition(new int[]{streamEventChainIndex, 0, BEFORE_WINDOW_DATA_INDEX, index});
} else {
throw new ExecutionPlanCreationException(attribute + " not exist in " + metaStreamEvent);
}
}
}
streamMappingElements.add(streamMappingElement);
}
return new SelectiveStreamEventPopulater(streamMappingElements);
}
}
| 45.422535 | 152 | 0.684651 |
3231f834b8842ce2d231c5466d5a1a78c5661628 | 843 | package org.webpieces.webserver.tokens;
import javax.inject.Singleton;
import org.webpieces.router.api.controller.actions.Action;
import org.webpieces.router.api.controller.actions.Actions;
@Singleton
public class TokenController {
public Action requiredNotExist() {
return Actions.renderThis();
}
public Action optionalNotExist() {
return Actions.renderThis();
}
public Action optionalNotExist2() {
return Actions.renderThis();
}
public Action optionalAndNull() {
return Actions.renderThis("client", null);
}
public Action requiredAndNull() {
return Actions.renderThis("client", null);
}
public Action escapingTokens() {
//The & html will be escaped so it shows up to the user as & (ie. in html it is & unless verbatim is used ..
return Actions.renderThis("someHtml", "<h1>Some& Title</h1>");
}
}
| 23.416667 | 115 | 0.73191 |
ab6453d798d99d0d002e84e1763d9c450032d302 | 1,308 | package cn.dreampie.common.util.scan;
import cn.dreampie.common.util.Lister;
import cn.dreampie.log.Logger;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
/**
* Created by Dreampie on 16/9/7.
*/
public class FileScaner extends Scaner<FileScaner> {
private static final Logger logger = Logger.getLogger(FileScaner.class);
private boolean isAbsolutePath = false;
public FileScaner isAbsolutePath(boolean isAbsolutePath) {
this.isAbsolutePath = isAbsolutePath;
return this;
}
/**
* 要扫描的类父级
*
* @return scaner
*/
public static FileScaner of() {
return new FileScaner().scanInJar(false).targetPattern("*.*");
}
/**
* 扫描文件
*
* @param baseDir
* @return
*/
protected Enumeration<URL> urlSolve(String baseDir) {
if (isAbsolutePath) {
try {
if (!baseDir.contains("/") && baseDir.contains(".")) {
baseDir = baseDir.replaceAll("\\.", "/");
}
File file = new File(baseDir);
return Collections.enumeration(Lister.<URL>of(file.toURI().toURL()));
} catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
}
} else {
super.urlSolve(baseDir);
}
return null;
}
}
| 22.551724 | 77 | 0.646789 |
12acb892d4ed00bc9e324527e94fea32911dfda0 | 3,041 | package com.cloudbees.groovy.cps.impl;
import com.cloudbees.groovy.cps.Block;
import com.cloudbees.groovy.cps.Continuation;
import com.cloudbees.groovy.cps.Env;
import com.cloudbees.groovy.cps.LValue;
import com.cloudbees.groovy.cps.LValueBlock;
import com.cloudbees.groovy.cps.Next;
/**
* "++x", "--x", "x++", or "x--" operator.
*
* This class is so named by Jesse Glick. When asked if my dictionary look up on the word "excrement" is accurate,
* he said: "given the number of stupid bugs caused by misuse of this syntax, yes!"
* So there we go.
*
* @author Kohsuke Kawaguchi
*/
public class ExcrementOperatorBlock implements Block {
/**
* "previous" for decrement and "next" for increment.
*/
private final String operatorMethod;
/**
* True if this is a prefix operator, false if it's a postfix.
*/
private final boolean prefix;
private final Block body;
private final SourceLocation loc;
public ExcrementOperatorBlock(SourceLocation loc, String operatorMethod, boolean prefix, LValueBlock body) {
this.loc = loc;
this.operatorMethod = operatorMethod;
this.prefix = prefix;
this.body = body.asLValue();
}
public Next eval(Env e, Continuation k) {
return new ContinuationImpl(e,k).then(body,e,fixLhs);
}
class ContinuationImpl extends ContinuationGroup {
final Continuation k;
final Env e;
LValue lhs;
Object before, after;
ContinuationImpl(Env e, Continuation k) {
this.e = e;
this.k = k;
}
/**
* LValue evaluated, then get the current value
*/
public Next fixLhs(Object lhs) {
this.lhs = (LValue)lhs;
return this.lhs.get(fixCur.bind(this));
}
/**
* Computed the current value of {@link LValue}.
* Next, evaluate the operator and capture the result
*/
public Next fixCur(Object v) {
this.before = v;
return methodCall(e, loc, calc, v, operatorMethod);
}
/**
* Result of the operator application obtained.
* Next, update the value.
*/
public Next calc(Object v) {
this.after = v;
// update the value.
return this.lhs.set(after,done.bind(this));
}
/**
* The result of the evaluation of the entire result depends on whether this is prefix or postfix
*/
public Next done(Object _) {
return k.receive(prefix?after:before);
}
}
static final ContinuationPtr fixLhs = new ContinuationPtr(ContinuationImpl.class,"fixLhs");
static final ContinuationPtr fixCur = new ContinuationPtr(ContinuationImpl.class,"fixCur");
static final ContinuationPtr calc = new ContinuationPtr(ContinuationImpl.class,"calc");
static final ContinuationPtr done = new ContinuationPtr(ContinuationImpl.class,"done");
private static final long serialVersionUID = 1L;
}
| 30.717172 | 114 | 0.630714 |
0d24898fc0fadc2581d0c2bf68ae88329eff988f | 226 | package ir.pint.soltoon.services.soltoonServices;
public interface SandboxService {
String getServiceName();
JobInfo startJob(JobOptions options);
boolean jobExists(String id);
JobInfo getJob(String id);
}
| 18.833333 | 49 | 0.747788 |
64318edfdabdb6a68cfeef77c5e23a5c3ac175c1 | 1,804 | package asw.database.entities;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "UserType")
public class Type implements Serializable{
private static final long serialVersionUID = 1L;
@Id
private int code;
private String type;
@OneToMany(mappedBy = "tipo")
private Set<Agent> usuarios = new HashSet<Agent>();
public Type(){}
/**
* Constructor de la clase Type. Crea un objeto
* al que se le asigna un código y un texto que identifica
* el tipo de usuario.
* @param code codigo del tipo. Tipo int
* @param type nombre asociado al tipo. Tipo String
*/
public Type(int code, String type) {
this.code = code;
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + code;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public String toString() {
return "Type [code=" + code + ", type=" + type + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Type other = (Type) obj;
if (code != other.code)
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Set<Agent> _getUsuarios() {
return this.usuarios;
}
}
| 19.608696 | 67 | 0.661863 |
8a000fd758ff39ba58229abd03ad33d1fbceb3e3 | 22,687 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.admingui.devtests;
import java.util.ArrayList;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.Select;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
*
* @author Jeremy Lv
*
*/
public class SecurityTest extends BaseSeleniumTestClass {
ArrayList<String> list = new ArrayList(); {list.add("server-config"); list.add("new-config");}
// @Test
// TODO: The page has a component without an explicit ID. Disabling the test for now.
public void testSecurityPage() {
createConfig("new-config");
for (String configName : list) {
gotoDasPage();
clickAndWait("treeForm:tree:configurations:" + configName + ":jvmSettings:jvmSettings_link");
clickAndWait("propertyForm:javaConfigTab:jvmOptions");
waitForElementPresent("TtlTxt_sun4", "JVM Options");
sleep(1000);
int emptyCount = getTableRowCountByValue("propertyForm:basicTable", "-Djava.security.manager", "col3:col1St", false);
if (emptyCount != 0 ){
String clickId = getTableRowByVal("propertyForm:basicTable", "-Djava.security.manager", "col3:col1St")+"col1:select";
clickByIdAction(clickId);
clickByIdAction("propertyForm:basicTable:topActionsGroup1:button1");
waitforBtnDisable("propertyForm:basicTable:topActionsGroup1:button1");
clickByIdAction("propertyForm:propertyContentPage:topButtons:saveButton");
assertTrue(isElementSaveSuccessful("label_sun4","New values successfully saved."));
}
sleep(1000);
int beforeCount = getTableRowCount("propertyForm:basicTable");
gotoDasPage();
clickAndWait("treeForm:tree:configurations:"+ configName +":security:security_link");
if (!driver.findElement(By.id("propertyForm:propertySheet:propertSectionTextField:securityManagerProp:sun_checkbox380")).isSelected()){
clickByIdAction("propertyForm:propertySheet:propertSectionTextField:securityManagerProp:sun_checkbox380");
}
clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton");
assertTrue(isElementSaveSuccessful("label_sun4","New values successfully saved."));
gotoDasPage();
clickAndWait("treeForm:tree:configurations:"+ configName +":jvmSettings:jvmSettings_link");
clickAndWait("propertyForm:javaConfigTab:jvmOptions");
sleep(1000);
int afterCount = getTableRowCount("propertyForm:basicTable");
assertEquals(afterCount, beforeCount+1);
// //delete security attribute if needed
// emptyCount = getTableRowCountByValue("propertyForm:basicTable", "-Djava.security.manager", "col3:col1St", false);
// if (emptyCount != 0 ){
// String clickId = getTableRowByVal("propertyForm:basicTable", "-Djava.security.manager", "col3:col1St")+"col1:select";
// clickByIdAction(clickId);
// clickByIdAction("propertyForm:basicTable:topActionsGroup1:button1");
// waitforBtnDisable("propertyForm:basicTable:topActionsGroup1:button1");
// clickByIdAction("propertyForm:propertyContentPage:topButtons:saveButton");
// isClassPresent("label_sun4");
// }
}
deleteConfig("new-config");
}
@Test
public void testNewSecurityRealm() {
final String realmName = "TestRealm" + generateRandomString();
final String contextName = "Context" + generateRandomString();
createConfig("new-config");
for (String configName : list) {
createRealm(configName, realmName, contextName);
//delete the related realm
String clickId = getTableRowByValue("propertyForm:realmsTable", realmName, "col1")+"col0:select";
clickByIdAction(clickId);
clickByIdAction("propertyForm:realmsTable:topActionsGroup1:button1");
closeAlertAndGetItsText();
waitforBtnDisable("propertyForm:realmsTable:topActionsGroup1:button1");
}
deleteConfig("new-config");
}
@Test
public void testAddUserToFileRealm() {
final String userId = "user" + generateRandomString();
final String password = "password" + generateRandomString();
createConfig("new-config");
for (String configName : list) {
addUserToRealm(configName, "file", userId, password);
//delete the added User for File Realm
String clickId = getTableRowByValue("propertyForm:users", userId, "col1")+"col0:select";
clickByIdAction(clickId);
clickByIdAction("propertyForm:users:topActionsGroup1:button1");
closeAlertAndGetItsText();
waitforBtnDisable("propertyForm:users:topActionsGroup1:button1");
}
deleteConfig("new-config");
}
@Test
public void testAddAuditModule() {
final String auditModuleName = "auditModule" + generateRandomString();
final String className = "org.glassfish.NonexistentModule";
createConfig("new-config");
for (String configName : list) {
gotoDasPage();
clickAndWait("treeForm:tree:configurations:" + configName + ":security:auditModules:auditModules_link");
clickAndWait("propertyForm:configs:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:IdTextProp:IdText", auditModuleName);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:classNameProp:ClassName", className);
int count = addTableRow("propertyForm:basicTable", "propertyForm:basicTable:topActionsGroup1:addSharedTableButton");
sleep(500);
setFieldValue("propertyForm:basicTable:rowGroup1:0:col2:col1St", "property");
sleep(500);
setFieldValue("propertyForm:basicTable:rowGroup1:0:col3:col1St", "value");
sleep(500);
setFieldValue("propertyForm:basicTable:rowGroup1:0:col4:col1St", "description");
clickAndWait("propertyForm:propertyContentPage:topButtons:newButton");
String prefix = getTableRowByValue("propertyForm:configs", auditModuleName, "col1");
assertEquals(auditModuleName, getText(prefix + "col1:link"));
String clickId = prefix + "col1:link";
clickByIdAction(clickId);
assertTableRowCount("propertyForm:basicTable", count);
clickAndWait("propertyForm:propertyContentPage:topButtons:cancelButton");
deleteRow("propertyForm:configs:topActionsGroup1:button1", "propertyForm:configs", auditModuleName);
}
deleteConfig("new-config");
}
@Test
public void testAddJaccModule() {
final String providerName = "testJaccProvider" + generateRandomString();
final String policyConfig = "com.example.Foo";
final String policyProvider = "com.example.Foo";
final String propName = "propName";
final String propValue = "propValue";
final String propDescription = generateRandomString();
createConfig("new-config");
for (String configName : list) {
gotoDasPage();
clickAndWait("treeForm:tree:configurations:" + configName + ":security:jaccProviders:jaccProviders_link");
clickAndWait("propertyForm:configs:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:IdTextProp:IdText", providerName);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:policyConfigProp:PolicyConfig", policyConfig);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:policyProviderProp:PolicyProvider", policyProvider);
int count = addTableRow("propertyForm:basicTable", "propertyForm:basicTable:topActionsGroup1:addSharedTableButton");
sleep(500);
setFieldValue("propertyForm:basicTable:rowGroup1:0:col2:col1St", propName);
sleep(500);
setFieldValue("propertyForm:basicTable:rowGroup1:0:col3:col1St", propValue);
sleep(500);
setFieldValue("propertyForm:basicTable:rowGroup1:0:col4:col1St", propDescription);
clickAndWait("propertyForm:propertyContentPage:topButtons:newButton");
String prefix = getTableRowByValue("propertyForm:configs", providerName, "col1");
assertEquals(providerName, getText(prefix + "col1:link"));
String clickId = prefix + "col1:link";
clickByIdAction(clickId);
assertEquals(policyConfig, getValue("propertyForm:propertySheet:propertSectionTextField:policyConfigProp:PolicyConfig", "value"));
assertEquals(policyProvider, getValue("propertyForm:propertySheet:propertSectionTextField:policyProviderProp:PolicyProvider", "value"));
assertEquals(propName, getValue("propertyForm:basicTable:rowGroup1:0:col2:col1St", "value"));
assertEquals(propValue, getValue("propertyForm:basicTable:rowGroup1:0:col3:col1St", "value"));
assertEquals(propDescription, getValue("propertyForm:basicTable:rowGroup1:0:col4:col1St", "value"));
assertTableRowCount("propertyForm:basicTable", count);
clickAndWait("propertyForm:propertyContentPage:topButtons:cancelButton");
deleteRow("propertyForm:configs:topActionsGroup1:button1", "propertyForm:configs", providerName);
}
deleteConfig("new-config");
}
@Test
public void testAddMessageSecurityConfiguration() {
final String providerName = "provider" + generateRandomString();
final String className = "com.example.Foo";
createConfig("new-config");
for (String configName : list) {
gotoDasPage();
clickAndWait("treeForm:tree:configurations:" + configName + ":security:messageSecurity:messageSecurity_link");
clickAndWait("treeForm:tree:configurations:" + configName + ":security:messageSecurity:SOAP:link");
clickAndWait("propertyForm:msgSecurityTabs:providers");
clickAndWait("propertyForm:configs:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:providerConfSection:ProviderIdTextProp:ProviderIdText", providerName);
setFieldValue("propertyForm:propertySheet:providerConfSection:ClassNameProp:ClassName", className);
int count = addTableRow("propertyForm:basicTable", "propertyForm:basicTable:topActionsGroup1:addSharedTableButton");
sleep(500);
setFieldValue("propertyForm:basicTable:rowGroup1:0:col2:col1St", "property");
sleep(500);
setFieldValue("propertyForm:basicTable:rowGroup1:0:col3:col1St", "value");
sleep(500);
setFieldValue("propertyForm:basicTable:rowGroup1:0:col4:col1St", "description");
clickAndWait("propertyForm:propertyContentPage:topButtons:newButton");
String prefix = getTableRowByValue("propertyForm:configs", providerName, "col1");
assertEquals(providerName, getText(prefix + "col1:authlayer"));
String clickId = prefix + "col1:authlayer";
clickByIdAction(clickId);
assertEquals(className, getValue("propertyForm:propertySheet:providerConfSection:ClassNameProp:ClassName", "value"));
assertTableRowCount("propertyForm:basicTable", count);
clickAndWait("propertyForm:propertyContentPage:topButtons:cancelButton");
//delete security attribute if needed
int emptyCount = getTableRowCountByValue("propertyForm:configs", providerName, "col1:authlayer", true);
if (emptyCount != 0 ){
clickId = getTableRowByValue("propertyForm:configs", providerName, "col1:authlayer")+"col0:select";
clickByIdAction(clickId);
clickByIdAction("propertyForm:configs:topActionsGroup1:button1");
closeAlertAndGetItsText();
waitforBtnDisable("propertyForm:configs:topActionsGroup1:button1");
}
}
deleteConfig("new-config");
}
@Test
public void testNewAdminPassword() {
gotoDasPage();
final String userPassword = "";
clickAndWait("treeForm:tree:nodes:nodes_link");
clickAndWait("propertyForm:domainTabs:adminPassword");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:newPasswordProp:NewPassword", userPassword);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:confirmPasswordProp:ConfirmPassword", userPassword);
clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton");
closeAlertAndGetItsText();
assertTrue(isElementSaveSuccessful("label_sun4","New values successfully saved."));
}
/*
* This test was add to test for regressions of GLASSFISH-14797
*/
@Test
public void testAddUserToRealmInRunningStandaloneInstance() {
final String instanceName = "server" + generateRandomString();
final String configName = instanceName + "-config";
final String contextName = "Context" + generateRandomString();
final String realmName = "newRealm";
final String userName = "user" + generateRandomNumber();
final StandaloneTest sat = new StandaloneTest();
try {
sat.createStandAloneInstance(instanceName);
sat.startInstance(instanceName);
createRealm(configName, realmName, contextName);
addUserToRealm(configName, realmName, userName, "password");
// Delete the user for good measure
deleteUserFromRealm(configName, realmName, userName);
} finally {
sat.gotoStandaloneInstancesPage();
sat.stopInstance(instanceName);
sat.deleteStandAloneInstance(instanceName);
}
}
/*
* This test was added to test for GLASSFISH-16126
* This test case need to be finished in the future
*/
// @Test
// public void testSecureAdministration() {
// gotoDasPage();
// clickAndWait("treeForm:tree:applicationServer:applicationServer_link");
// clickAndWait("propertyForm:propertyContentPage:secureAdmin");
// if (driver.findElement(By.className("TtlTxt_sun4")).getText().equals("Secure Administration")) {
// clickAndWait("form:propertyContentPage:topButtons:enableSecureAdminButton");
// closeAlertAndGetItsText();
// sleep(10000);
// gotoDasPage();
// clickAndWait("treeForm:tree:applicationServer:applicationServer_link");
// clickAndWait("propertyForm:propertyContentPage:secureAdmin");
// selenium.click("form:propertyContentPage:topButtons:disableSecureAdminButton");
// closeAlertAndGetItsText();
// sleep(10000);
// }
// }
// //Need to be finished in the future
// @Test
// public void testRedirectAfterLogin() {
// gotoDasPage();
// final String newUser = "user" + generateRandomString();
// final String realmName = "admin-realm";
// final String newPass = generateRandomString();
//
// try {
// addUserToRealm("server-config", realmName, newUser, newPass);
// // http://localhost:4848/common/help/help.jsf?contextRef=/resource/common/en/help/ref-developercommontasks.html
// clickByIdAction("Masthead:logoutLink");
// driver.close();
// driver.get("http://localhost:4848/common/help/help.jsf?contextRef=/resource/common/en/help/ref-developercommontasks.html");
// driver.close();
//// handleLogin(newUser, newPass, "The Common Tasks page provides shortcuts for common Administration Console tasks.");
// } finally {
// clickByIdAction("Masthead:logoutLink");
// gotoDasPage();
//// handleLogin();
// deleteUserFromRealm("server-config", realmName, newUser);
// }
// }
public void createConfig(String configName) {
gotoDasPage();
clickAndWait("treeForm:tree:configurations:configurations_link");
int emptyCount = getTableRowCountByValue("propertyForm:configs", "new-config", "col1:link", true);
if (emptyCount == 0) {
clickAndWait("propertyForm:configs:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:NameProp:Name", configName);
clickAndWait("propertyForm:propertyContentPage:topButtons:okButton");
String prefix = getTableRowByValue("propertyForm:configs", configName, "col1");
assertEquals(configName, getText(prefix + "col1:link"));
}
}
private void deleteConfig(String configName) {
gotoDasPage();
clickAndWait("treeForm:tree:configurations:configurations_link");
deleteRow("propertyForm:configs:topActionsGroup1:button1", "propertyForm:configs", configName);
}
public void createRealm(String configName, String realmName, String contextName) {
gotoDasPage();
clickAndWait("treeForm:tree:configurations:" + configName + ":security:realms:realms_link");
clickAndWait("propertyForm:realmsTable:topActionsGroup1:newButton");
setFieldValue("form1:propertySheet:propertySectionTextField:NameTextProp:NameText", realmName);
Select select = new Select(driver.findElement(By.id("form1:propertySheet:propertySectionTextField:cp:Classname")));
select.selectByVisibleText("com.sun.enterprise.security.auth.realm.file.FileRealm");
setFieldValue("form1:fileSection:jaax:jaax", contextName);
setFieldValue("form1:fileSection:keyFile:keyFile", "${com.sun.aas.instanceRoot}/config/testfile");
clickAndWait("form1:propertyContentPage:topButtons:newButton");
String prefix = getTableRowByValue("propertyForm:realmsTable", realmName, "col1");
assertEquals(realmName, getText(prefix + "col1:link"));
}
public void addUserToRealm(String configName, String realmName, String userName, String password) {
gotoDasPage();
clickAndWait("treeForm:tree:configurations:" + configName + ":security:realms:realms_link");
String prefix = getTableRowByValue("propertyForm:realmsTable", realmName, "col1");
assertEquals(realmName, getText(prefix + "col1:link"));
String clickId = prefix + "col1:link";
clickByIdAction(clickId);
waitForElementPresent("TtlTxt_sun4","Edit Realm");
clickAndWait("form1:propertyContentPage:manageUsersButton");
clickAndWait("propertyForm:users:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:userIdProp:UserId", userName);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:newPasswordProp:NewPassword", password);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:confirmPasswordProp:ConfirmPassword", password);
clickAndWait("propertyForm:propertyContentPage:topButtons:newButton");
String prefix1 = getTableRowByValue("propertyForm:users", userName, "col1");
assertEquals(userName, getText(prefix1 + "col1:link"));
}
public void deleteUserFromRealm(String configName, String realmName, String userName) {
clickAndWait("treeForm:tree:configurations:" + configName + ":security:realms:realms_link");
String prefix = getTableRowByValue("propertyForm:realmsTable", realmName, "col1");
String clickId = prefix + "col1:link";
clickByIdAction(clickId);
clickAndWait("form1:propertyContentPage:manageUsersButton");
//delete security attribute if needed
int emptyCount = getTableRowCountByValue("propertyForm:users", userName, "col1:link", true);
if (emptyCount != 0 ){
clickId = getTableRowByValue("propertyForm:users", userName, "col1:link")+"col0:select";
clickByIdAction(clickId);
clickByIdAction("propertyForm:users:topActionsGroup1:button1");
closeAlertAndGetItsText();
waitforBtnDisable("propertyForm:users:topActionsGroup1:button1");
}
}
}
| 50.081678 | 148 | 0.679861 |
eaf1246de30f5157e1a39f751b51b5d40c86a28b | 24,876 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dump/v1/dump.proto
package io.opencensus.proto.dump;
/**
* <pre>
* Used to dump spans for later store&process
* </pre>
*
* Protobuf type {@code opencensus.proto.dump.v1.DumpSpans}
*/
public final class DumpSpans extends com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:opencensus.proto.dump.v1.DumpSpans)
DumpSpansOrBuilder {
private static final long serialVersionUID = 0L;
// Use DumpSpans.newBuilder() to construct.
private DumpSpans(final com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DumpSpans() {
this.spans_ = java.util.Collections.emptyList();
}
@Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private DumpSpans(final com.google.protobuf.CodedInputStream input,
final com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new NullPointerException();
}
int mutable_bitField0_ = 0;
final com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
final int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
this.spans_ = new java.util.ArrayList<>();
mutable_bitField0_ |= 0x00000001;
}
this.spans_.add(
input.readMessage(io.opencensus.proto.trace.v1.Span.parser(), extensionRegistry));
break;
}
default: {
if (!this.parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (final com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (final java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if ((mutable_bitField0_ & 0x00000001) != 0) {
this.spans_ = java.util.Collections.unmodifiableList(this.spans_);
}
this.unknownFields = unknownFields.build();
this.makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return DumpProto.internal_static_opencensus_proto_dump_v1_DumpSpans_descriptor;
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return DumpProto.internal_static_opencensus_proto_dump_v1_DumpSpans_fieldAccessorTable
.ensureFieldAccessorsInitialized(DumpSpans.class, Builder.class);
}
public static final int SPANS_FIELD_NUMBER = 1;
private java.util.List<io.opencensus.proto.trace.v1.Span> spans_;
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
@Override
public java.util.List<io.opencensus.proto.trace.v1.Span> getSpansList() {
return this.spans_;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
@Override
public java.util.List<? extends io.opencensus.proto.trace.v1.SpanOrBuilder> getSpansOrBuilderList() {
return this.spans_;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
@Override
public int getSpansCount() {
return this.spans_.size();
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
@Override
public io.opencensus.proto.trace.v1.Span getSpans(final int index) {
return this.spans_.get(index);
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
@Override
public io.opencensus.proto.trace.v1.SpanOrBuilder getSpansOrBuilder(final int index) {
return this.spans_.get(index);
}
private byte memoizedIsInitialized = -1;
@Override
public final boolean isInitialized() {
final byte isInitialized = this.memoizedIsInitialized;
if (isInitialized == 1) {
return true;
}
if (isInitialized == 0) {
return false;
}
this.memoizedIsInitialized = 1;
return true;
}
@Override
public void writeTo(final com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
for (int i = 0; i < this.spans_.size(); i++) {
output.writeMessage(1, this.spans_.get(i));
}
this.unknownFields.writeTo(output);
}
@Override
public int getSerializedSize() {
int size = this.memoizedSize;
if (size != -1) {
return size;
}
size = 0;
for (int i = 0; i < this.spans_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, this.spans_.get(i));
}
size += this.unknownFields.getSerializedSize();
this.memoizedSize = size;
return size;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof DumpSpans)) {
return super.equals(obj);
}
final DumpSpans other = (DumpSpans) obj;
if (!this.getSpansList().equals(other.getSpansList())) {
return false;
}
if (!this.unknownFields.equals(other.unknownFields)) {
return false;
}
return true;
}
@SuppressWarnings("unchecked")
@Override
public int hashCode() {
if (this.memoizedHashCode != 0) {
return this.memoizedHashCode;
}
int hash = 41;
hash = 19 * hash + getDescriptor().hashCode();
if (this.getSpansCount() > 0) {
hash = 37 * hash + SPANS_FIELD_NUMBER;
hash = 53 * hash + this.getSpansList().hashCode();
}
hash = 29 * hash + this.unknownFields.hashCode();
this.memoizedHashCode = hash;
return hash;
}
public static DumpSpans parseFrom(final java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static DumpSpans parseFrom(final java.nio.ByteBuffer data,
final com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static DumpSpans parseFrom(final com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static DumpSpans parseFrom(final com.google.protobuf.ByteString data,
final com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static DumpSpans parseFrom(final byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static DumpSpans parseFrom(final byte[] data,
final com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static DumpSpans parseFrom(final java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static DumpSpans parseFrom(final java.io.InputStream input,
final com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input,
extensionRegistry);
}
public static DumpSpans parseDelimitedFrom(final java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static DumpSpans parseDelimitedFrom(final java.io.InputStream input,
final com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input,
extensionRegistry);
}
public static DumpSpans parseFrom(final com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static DumpSpans parseFrom(final com.google.protobuf.CodedInputStream input,
final com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input,
extensionRegistry);
}
@Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(final DumpSpans prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@Override
protected Builder newBuilderForType(final BuilderParent parent) {
final Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Used to dump spans for later store&process
* </pre>
*
* Protobuf type {@code opencensus.proto.dump.v1.DumpSpans}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:opencensus.proto.dump.v1.DumpSpans)
DumpSpansOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return DumpProto.internal_static_opencensus_proto_dump_v1_DumpSpans_descriptor;
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return DumpProto.internal_static_opencensus_proto_dump_v1_DumpSpans_fieldAccessorTable
.ensureFieldAccessorsInitialized(DumpSpans.class, Builder.class);
}
// Construct using io.opencensus.proto.dump.DumpSpans.newBuilder()
private Builder() {
this.maybeForceBuilderInitialization();
}
private Builder(final BuilderParent parent) {
super(parent);
this.maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
this.getSpansFieldBuilder();
}
}
@Override
public Builder clear() {
super.clear();
if (this.spansBuilder_ == null) {
this.spans_ = java.util.Collections.emptyList();
this.bitField0_ = this.bitField0_ & ~0x00000001;
} else {
this.spansBuilder_.clear();
}
return this;
}
@Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return DumpProto.internal_static_opencensus_proto_dump_v1_DumpSpans_descriptor;
}
@Override
public DumpSpans getDefaultInstanceForType() {
return DumpSpans.getDefaultInstance();
}
@Override
public DumpSpans build() {
final DumpSpans result = this.buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@Override
public DumpSpans buildPartial() {
final DumpSpans result = new DumpSpans(this);
@SuppressWarnings("unused")
final int from_bitField0_ = this.bitField0_;
if (this.spansBuilder_ == null) {
if ((this.bitField0_ & 0x00000001) != 0) {
this.spans_ = java.util.Collections.unmodifiableList(this.spans_);
this.bitField0_ = this.bitField0_ & ~0x00000001;
}
result.spans_ = this.spans_;
} else {
result.spans_ = this.spansBuilder_.build();
}
this.onBuilt();
return result;
}
@Override
public Builder clone() {
return super.clone();
}
@Override
public Builder setField(final com.google.protobuf.Descriptors.FieldDescriptor field,
final Object value) {
return super.setField(field, value);
}
@Override
public Builder clearField(final com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@Override
public Builder clearOneof(final com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@Override
public Builder setRepeatedField(final com.google.protobuf.Descriptors.FieldDescriptor field,
final int index, final Object value) {
return super.setRepeatedField(field, index, value);
}
@Override
public Builder addRepeatedField(final com.google.protobuf.Descriptors.FieldDescriptor field,
final Object value) {
return super.addRepeatedField(field, value);
}
@Override
public Builder mergeFrom(final com.google.protobuf.Message other) {
if (other instanceof DumpSpans) {
return this.mergeFrom((DumpSpans) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(final DumpSpans other) {
if (other == DumpSpans.getDefaultInstance()) {
return this;
}
if (this.spansBuilder_ == null) {
if (!other.spans_.isEmpty()) {
if (this.spans_.isEmpty()) {
this.spans_ = other.spans_;
this.bitField0_ = this.bitField0_ & ~0x00000001;
} else {
this.ensureSpansIsMutable();
this.spans_.addAll(other.spans_);
}
this.onChanged();
}
} else {
if (!other.spans_.isEmpty()) {
if (this.spansBuilder_.isEmpty()) {
this.spansBuilder_.dispose();
this.spansBuilder_ = null;
this.spans_ = other.spans_;
this.bitField0_ = this.bitField0_ & ~0x00000001;
this.spansBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? this.getSpansFieldBuilder()
: null;
} else {
this.spansBuilder_.addAllMessages(other.spans_);
}
}
}
this.mergeUnknownFields(other.unknownFields);
this.onChanged();
return this;
}
@Override
public final boolean isInitialized() {
return true;
}
@Override
public Builder mergeFrom(final com.google.protobuf.CodedInputStream input,
final com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
DumpSpans parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (final com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (DumpSpans) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
this.mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<io.opencensus.proto.trace.v1.Span> spans_ =
java.util.Collections.emptyList();
private void ensureSpansIsMutable() {
if (!((this.bitField0_ & 0x00000001) != 0)) {
this.spans_ = new java.util.ArrayList<>(this.spans_);
this.bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<io.opencensus.proto.trace.v1.Span, io.opencensus.proto.trace.v1.Span.Builder, io.opencensus.proto.trace.v1.SpanOrBuilder> spansBuilder_;
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
@Override
public java.util.List<io.opencensus.proto.trace.v1.Span> getSpansList() {
if (this.spansBuilder_ == null) {
return java.util.Collections.unmodifiableList(this.spans_);
} else {
return this.spansBuilder_.getMessageList();
}
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
@Override
public int getSpansCount() {
if (this.spansBuilder_ == null) {
return this.spans_.size();
} else {
return this.spansBuilder_.getCount();
}
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
@Override
public io.opencensus.proto.trace.v1.Span getSpans(final int index) {
if (this.spansBuilder_ == null) {
return this.spans_.get(index);
} else {
return this.spansBuilder_.getMessage(index);
}
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public Builder setSpans(final int index, final io.opencensus.proto.trace.v1.Span value) {
if (this.spansBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
this.ensureSpansIsMutable();
this.spans_.set(index, value);
this.onChanged();
} else {
this.spansBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public Builder setSpans(final int index,
final io.opencensus.proto.trace.v1.Span.Builder builderForValue) {
if (this.spansBuilder_ == null) {
this.ensureSpansIsMutable();
this.spans_.set(index, builderForValue.build());
this.onChanged();
} else {
this.spansBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public Builder addSpans(final io.opencensus.proto.trace.v1.Span value) {
if (this.spansBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
this.ensureSpansIsMutable();
this.spans_.add(value);
this.onChanged();
} else {
this.spansBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public Builder addSpans(final int index, final io.opencensus.proto.trace.v1.Span value) {
if (this.spansBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
this.ensureSpansIsMutable();
this.spans_.add(index, value);
this.onChanged();
} else {
this.spansBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public Builder addSpans(final io.opencensus.proto.trace.v1.Span.Builder builderForValue) {
if (this.spansBuilder_ == null) {
this.ensureSpansIsMutable();
this.spans_.add(builderForValue.build());
this.onChanged();
} else {
this.spansBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public Builder addSpans(final int index,
final io.opencensus.proto.trace.v1.Span.Builder builderForValue) {
if (this.spansBuilder_ == null) {
this.ensureSpansIsMutable();
this.spans_.add(index, builderForValue.build());
this.onChanged();
} else {
this.spansBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public Builder addAllSpans(final Iterable<? extends io.opencensus.proto.trace.v1.Span> values) {
if (this.spansBuilder_ == null) {
this.ensureSpansIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, this.spans_);
this.onChanged();
} else {
this.spansBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public Builder clearSpans() {
if (this.spansBuilder_ == null) {
this.spans_ = java.util.Collections.emptyList();
this.bitField0_ = this.bitField0_ & ~0x00000001;
this.onChanged();
} else {
this.spansBuilder_.clear();
}
return this;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public Builder removeSpans(final int index) {
if (this.spansBuilder_ == null) {
this.ensureSpansIsMutable();
this.spans_.remove(index);
this.onChanged();
} else {
this.spansBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public io.opencensus.proto.trace.v1.Span.Builder getSpansBuilder(final int index) {
return this.getSpansFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
@Override
public io.opencensus.proto.trace.v1.SpanOrBuilder getSpansOrBuilder(final int index) {
if (this.spansBuilder_ == null) {
return this.spans_.get(index);
} else {
return this.spansBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
@Override
public java.util.List<? extends io.opencensus.proto.trace.v1.SpanOrBuilder> getSpansOrBuilderList() {
if (this.spansBuilder_ != null) {
return this.spansBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(this.spans_);
}
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public io.opencensus.proto.trace.v1.Span.Builder addSpansBuilder() {
return this.getSpansFieldBuilder()
.addBuilder(io.opencensus.proto.trace.v1.Span.getDefaultInstance());
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public io.opencensus.proto.trace.v1.Span.Builder addSpansBuilder(final int index) {
return this.getSpansFieldBuilder().addBuilder(index,
io.opencensus.proto.trace.v1.Span.getDefaultInstance());
}
/**
* <code>repeated .opencensus.proto.trace.v1.Span spans = 1;</code>
*/
public java.util.List<io.opencensus.proto.trace.v1.Span.Builder> getSpansBuilderList() {
return this.getSpansFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<io.opencensus.proto.trace.v1.Span, io.opencensus.proto.trace.v1.Span.Builder, io.opencensus.proto.trace.v1.SpanOrBuilder> getSpansFieldBuilder() {
if (this.spansBuilder_ == null) {
this.spansBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<>(
this.spans_, (this.bitField0_ & 0x00000001) != 0, this.getParentForChildren(),
this.isClean());
this.spans_ = null;
}
return this.spansBuilder_;
}
@Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:opencensus.proto.dump.v1.DumpSpans)
}
// @@protoc_insertion_point(class_scope:opencensus.proto.dump.v1.DumpSpans)
private static final DumpSpans DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new DumpSpans();
}
public static DumpSpans getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DumpSpans> PARSER =
new com.google.protobuf.AbstractParser<>() {
@Override
public DumpSpans parsePartialFrom(final com.google.protobuf.CodedInputStream input,
final com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new DumpSpans(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<DumpSpans> parser() {
return PARSER;
}
@Override
public com.google.protobuf.Parser<DumpSpans> getParserForType() {
return PARSER;
}
@Override
public DumpSpans getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| 31.409091 | 201 | 0.662767 |
f4f823d814e7da9ca381a6c792e2afc872bb5946 | 4,200 | package com.blacknebula.testcherry.codeinsight;
import com.blacknebula.testcherry.model.TestCherrySettings;
import com.blacknebula.testcherry.testframework.SupportedFrameworks;
import com.intellij.openapi.options.BaseConfigurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import org.jetbrains.annotations.Nls;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
/**
* User: Jaime Hablutzel
*/
public class TestCherryConfigurable extends BaseConfigurable implements SearchableConfigurable {
private static final String EMPTY_STRING = "";
private final Project myProject;
private MyComponent myComponent;
public TestCherryConfigurable(Project myProject) {
this.myProject = myProject;
}
@Override
public String getId() {
return getDisplayName(); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Runnable enableSearch(String option) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Nls
@Override
public String getDisplayName() {
return "Test Cherry";
}
@Override
public String getHelpTopic() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public JComponent createComponent() {
List<String> strings = new ArrayList<String>();
strings.add("-");
SupportedFrameworks[] frameworks = SupportedFrameworks.values();
for (SupportedFrameworks framework : frameworks) {
strings.add(framework.toString());
}
DefaultComboBoxModel aModel = new DefaultComboBoxModel(strings.toArray());
TestCherrySettings casesSettings = TestCherrySettings.getInstance(myProject);
myComponent = new MyComponent();
if (casesSettings != null) {
addComboBoxItems(aModel, casesSettings);
}
//To change body of implemented methods use File | Settings | File Templates.
return myComponent.getPanel();
}
@Override
public void apply() throws ConfigurationException {
// get settings holder
TestCherrySettings casesSettings = TestCherrySettings.getInstance(myProject);
// persist currently selected test framework
String s = myComponent.comboBox.getSelectedItem().toString();
if (!s.equals("-")) {
casesSettings.setTestFramework(s);
} else {
casesSettings.setTestFramework(EMPTY_STRING);
}
}
@Override
public void reset() {
}
@Override
public boolean isModified() {
TestCherrySettings casesSettings = TestCherrySettings.getInstance(myProject);
String o = (String) myComponent.comboBox.getSelectedItem();
String s = casesSettings.getTestFramework();
if (o.equals("-")) {
return !s.equals(EMPTY_STRING);
} else {
return !o.equals(s);
}
}
@Override
public void disposeUIResources() {
}
private void addComboBoxItems(DefaultComboBoxModel aModel, TestCherrySettings casesSettings) {
String testFramework = casesSettings.getTestFramework();
if (!testFramework.equals(EMPTY_STRING)) {
aModel.setSelectedItem(testFramework);
}
myComponent.setModel(aModel);
}
private static class MyComponent {
private final JComboBox comboBox;
private final JPanel panel;
private MyComponent() {
comboBox = new ComboBox();
panel = new JPanel();
panel.add(comboBox);
}
private MyComponent setModel(ComboBoxModel model) {
comboBox.setModel(model);
return this;
}
public JPanel getPanel() {
return panel;
}
}
}
| 29.370629 | 112 | 0.64119 |
d196338240b424ccf5e77d1cadb829080d4ab4b3 | 733 | package uff.dew.avp.localqueryprocessor.localquerytask;
/**
*
* @author Alex
*/
public class LQT_Msg_IntervalFinished extends LQT_Message {
private int a_intervalBeginning;
private int a_intervalEnd;
/** Creates a new instance of LQT_Msg_IntervalFinished */
public LQT_Msg_IntervalFinished( int idSender, int intervalBeginning, int intervalEnd ) {
super( idSender );
a_intervalBeginning = intervalBeginning;
a_intervalEnd = intervalEnd;
}
public int getType() {
return MSG_INTERVALFINISHED;
}
public int getIntervalBeginning() {
return a_intervalBeginning;
}
public int getIntervalEnd() {
return a_intervalEnd;
}
}
| 23.645161 | 93 | 0.675307 |
bb923409b54498579f33eef30b14ee75122c4cde | 8,093 | /*
* Copyright 2016 Google 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
*
* 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.hyperaware.conference.android.ui.favsession;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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.hyperaware.conference.android.R;
import com.hyperaware.conference.android.logging.Logging;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A utility class that manages the functionality of "favorites" buttons.
*
*/
@MainThread
public class FavSessionButtonManager {
private static final Logger LOGGER = Logging.getLogger(FavSessionButtonManager.class);
private final FirebaseDatabase fdb;
private final FirebaseAuth auth;
private final AuthRequiredListener authRequiredListener;
private final MyAuthStateListener authStateListener = new MyAuthStateListener();
private MyUserFavoritesListener favoritesListener;
private DatabaseReference userFavoriteSessionsRef;
private FirebaseUser user;
private final HashMap<String, HashSet<ImageButton>> sessionButtons = new HashMap<>();
private final HashSet<String> favorites = new HashSet<>();
public FavSessionButtonManager(@NonNull final FirebaseDatabase fdb, @NonNull final FirebaseAuth auth, @NonNull final AuthRequiredListener arl) {
this.fdb = fdb;
this.auth = auth;
this.authRequiredListener = arl;
}
public void start() {
auth.addAuthStateListener(authStateListener);
}
public void stop() {
auth.removeAuthStateListener(authStateListener);
stopListeningFavorites();
}
public void attach(@NonNull final ImageButton button, @NonNull final String session_id) {
button.setOnClickListener(new MyFavSessionButtonOnClickListener(session_id));
HashSet<ImageButton> buttons = sessionButtons.get(session_id);
if (buttons == null) {
buttons = new HashSet<>();
sessionButtons.put(session_id, buttons);
}
buttons.add(button);
updateButton(button, session_id);
}
public void detach(@NonNull final ImageButton button, @NonNull final String session_id) {
button.setOnClickListener(null);
final HashSet<ImageButton> buttons = sessionButtons.get(session_id);
if (buttons != null) {
buttons.remove(button);
}
}
private void updateButton(final ImageButton button, final String session_id) {
boolean is_fav = favorites.contains(session_id);
final int draw_res = is_fav ?
R.drawable.ic_favorite_black_24dp :
R.drawable.ic_favorite_border_black_24dp;
button.setImageResource(draw_res);
button.setOnClickListener(new MyFavSessionButtonOnClickListener(session_id));
}
private void startListeningFavorites() {
userFavoriteSessionsRef = fdb.getReference("/users/" + user.getUid() + "/favorites/sessions");
favoritesListener = new MyUserFavoritesListener();
userFavoriteSessionsRef.addChildEventListener(favoritesListener);
}
private void stopListeningFavorites() {
if (userFavoriteSessionsRef != null) {
userFavoriteSessionsRef.removeEventListener(favoritesListener);
userFavoriteSessionsRef = null;
favoritesListener = null;
favorites.clear();
for (final Map.Entry<String, HashSet<ImageButton>> entry : sessionButtons.entrySet()) {
final String session_id = entry.getKey();
final HashSet<ImageButton> buttons = entry.getValue();
for (final ImageButton button : buttons) {
updateButton(button, session_id);
}
}
}
}
private class MyAuthStateListener implements FirebaseAuth.AuthStateListener {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if (user != null) {
startListeningFavorites();
}
else {
stopListeningFavorites();
}
}
}
private class MyFavSessionButtonOnClickListener implements View.OnClickListener {
private final String sessionId;
public MyFavSessionButtonOnClickListener(final String session_id) {
this.sessionId = session_id;
}
@Override
public void onClick(final View view) {
// Require a currently signed in user in order to toggle favorites
if (user != null) {
toggleFavorite();
}
else {
authRequiredListener.onAuthRequired((ImageButton) view, sessionId);
}
}
private void toggleFavorite() {
boolean is_fav = favorites.contains(sessionId);
if (is_fav) {
favorites.remove(sessionId);
userFavoriteSessionsRef.child(sessionId).removeValue();
}
else {
favorites.add(sessionId);
userFavoriteSessionsRef.child(sessionId).setValue(true);
}
}
}
private class MyUserFavoritesListener implements ChildEventListener {
@Override
public void onChildAdded(DataSnapshot data, String previousChildName) {
final String session_id = data.getKey();
boolean is_fav = data.getValue(Boolean.class);
if (is_fav) {
favorites.add(session_id);
}
else {
favorites.remove(session_id);
}
updateButtons(session_id);
}
@Override
public void onChildChanged(DataSnapshot data, String previousChildName) {
final String session_id = data.getKey();
boolean is_fav = data.getValue(Boolean.class);
if (is_fav) {
favorites.add(session_id);
}
else {
favorites.remove(session_id);
}
updateButtons(session_id);
}
@Override
public void onChildRemoved(DataSnapshot data) {
final String session_id = data.getKey();
favorites.remove(session_id);
updateButtons(session_id);
}
@Override
public void onChildMoved(DataSnapshot data, String s) {
// Don't care
}
@Override
public void onCancelled(DatabaseError databaseError) {
LOGGER.log(Level.SEVERE, "onCancelled", databaseError.toException());
}
private void updateButtons(String session_id) {
final HashSet<ImageButton> buttons = sessionButtons.get(session_id);
if (buttons != null) {
for (final ImageButton button : buttons) {
updateButton(button, session_id);
}
}
}
}
public interface AuthRequiredListener {
void onAuthRequired(ImageButton view, String sessionId);
}
}
| 34.438298 | 148 | 0.651798 |
1778539f2b2107e4b9a6e32e7700e1be5f2758e7 | 3,059 | /*
* The MIT License (MIT)
*
* Copyright (c) 2020-2021 tools4j.org (Marco Terzer, Anton Anufriev)
*
* 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 org.tools4j.elara.format;
import org.agrona.DirectBuffer;
public enum Hex {
;
private static final char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
private static final char BYTE_SPACER = ' ';
private static final String[] DECIMAL_SEPARATORS = {" : ", " :: ", " ::: "};
public static String hex(final DirectBuffer buffer) {
return hex(buffer, 0, buffer.capacity());
}
public static String hex(final DirectBuffer buffer, final int offset, final int length) {
return hex(buffer, offset, length, true, true);
}
public static String hex(final DirectBuffer buffer, final int offset, final int length,
final boolean byteSeparators,
final boolean decimalSeparators) {
final StringBuilder sb = new StringBuilder(length * 3);
for (int i = 0; i < length; i++) {
final byte b = buffer.getByte(offset + i);
final int b0 = b & 0xf;
final int b1 = (b >>> 4) & 0xf;
if (i > 0) {
appendSpacer(sb, i, byteSeparators, decimalSeparators);
}
sb.append(HEX_CHARS[b0]);
sb.append(HEX_CHARS[b1]);
}
return sb.toString();
}
private static void appendSpacer(final StringBuilder sb, final int index,
final boolean byteSeparators,
final boolean decimalSeparators) {
if (decimalSeparators && (index % 10) == 0) {
if ((index % 100) == 0) {
sb.append((index % 1000) == 0 ? DECIMAL_SEPARATORS[2] : DECIMAL_SEPARATORS[1]);
} else {
sb.append(DECIMAL_SEPARATORS[0]);
}
} else if (byteSeparators) {
sb.append(BYTE_SPACER);
}
}
}
| 41.337838 | 110 | 0.619483 |
e61abb53e7fd35d85d89aff75e2dc722f6b53bd7 | 4,745 | package io.turntabl.dataaccess;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class RestAPIConsume {
public static Optional<List<Client>> getClients(String url){
String location = url;
var client = HttpClient.newBuilder().build();
URI uri = null;
try {
uri = new URI(location);
} catch (
URISyntaxException e) {
e.printStackTrace();
System.exit(1);
}
var req = HttpRequest.newBuilder(uri).build();
try {
var response = client.send(req, HttpResponse.BodyHandlers.ofString(Charset.defaultCharset()));
var jsonData = jsonStringToClientObject(response.body());
return Optional.of(jsonData);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return Optional.empty();
}
private static List<Client> jsonStringToClientObject(String json) {
ObjectMapper objectMapper = new ObjectMapper();
try {
TypeFactory typeFactory = objectMapper.getTypeFactory();
CollectionType collectionType = typeFactory.constructCollectionType(
List.class, Client.class);
return objectMapper.readValue(json, collectionType);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Client parseJsonToClientObj(String json) {
var mapper = new ObjectMapper();
var typeRef = new TypeReference<HashMap<String,Object>>() {};
try {
Map<String, Object> mJson = mapper.readValue(json, typeRef);
Client client = new Client();
client.setName((String) mJson.get("name"));
client.setAddress((String) mJson.get("address"));
client.setTelephoneNumber((String) mJson.get("telephoneNumber"));
client.setEmail((String) mJson.get("email"));
return client;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static boolean post(String uri, String data) throws Exception {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(data))
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString(Charset.defaultCharset()));
return (response.statusCode() == 200);
}
public static Optional<Client> delete(String uri) throws Exception {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
//.header("Content-Type", "application/json")
.DELETE()
.build();
try {
var response = client.send(request, HttpResponse.BodyHandlers.ofString(Charset.defaultCharset()));
var jsonData = parseJsonToClientObj(response.body());
return Optional.of(jsonData);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return Optional.empty();
}
public static Optional<Client> recover(String uri) throws Exception {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.build();
try {
var response = client.send(request, HttpResponse.BodyHandlers.ofString(Charset.defaultCharset()));
var jsonData = parseJsonToClientObj(response.body());
return Optional.of(jsonData);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return Optional.empty();
}
public static String clientObjectToJsonString(Client client) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(client);
}
}
| 37.65873 | 110 | 0.633087 |
310f6499e40581ac968c9da708c3d97f0ec4d798 | 1,520 | package com.alipay.api.response;
import java.util.List;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
import com.alipay.api.domain.UserTaskView;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.merchant.weike.settle.query response.
*
* @author auto create
* @since 1.0, 2019-05-30 12:10:01
*/
public class AlipayMerchantWeikeSettleQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 4237941929283894774L;
/**
* 外部业务号
*/
@ApiField("out_biz_no")
private String outBizNo;
/**
* 分页查询页号,从1开始
*/
@ApiField("page_no")
private Long pageNo;
/**
* 分页查询页大小,最大100
*/
@ApiField("page_size")
private Long pageSize;
/**
* 用户任务列表
*/
@ApiListField("user_task_views")
@ApiField("user_task_view")
private List<UserTaskView> userTaskViews;
public void setOutBizNo(String outBizNo) {
this.outBizNo = outBizNo;
}
public String getOutBizNo( ) {
return this.outBizNo;
}
public void setPageNo(Long pageNo) {
this.pageNo = pageNo;
}
public Long getPageNo( ) {
return this.pageNo;
}
public void setPageSize(Long pageSize) {
this.pageSize = pageSize;
}
public Long getPageSize( ) {
return this.pageSize;
}
public void setUserTaskViews(List<UserTaskView> userTaskViews) {
this.userTaskViews = userTaskViews;
}
public List<UserTaskView> getUserTaskViews( ) {
return this.userTaskViews;
}
}
| 20.540541 | 77 | 0.690789 |
c97d1d0db6eafaa6a52a17d4ae2f4a22469f3eb5 | 37,584 | package com.alibaba.datax.plugin.writer.hdfswriter;
import com.alibaba.datax.common.element.Column;
import com.alibaba.datax.common.element.Record;
import com.alibaba.datax.common.exception.DataXException;
import com.alibaba.datax.common.plugin.RecordReceiver;
import com.alibaba.datax.common.plugin.TaskPluginCollector;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.avro.Conversions;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.generic.GenericRecordBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.common.type.Timestamp;
import org.apache.hadoop.hive.ql.exec.vector.BytesColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.DecimalColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.DoubleColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.TimestampColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.JobContext;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.orc.CompressionKind;
import org.apache.orc.OrcFile;
import org.apache.orc.TypeDescription;
import org.apache.orc.Writer;
import org.apache.parquet.avro.AvroParquetWriter;
import org.apache.parquet.hadoop.ParquetWriter;
import org.apache.parquet.hadoop.metadata.CompressionCodecName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class HdfsHelper
{
public static final Logger LOG = LoggerFactory.getLogger(HdfsHelper.class);
public static final String HADOOP_SECURITY_AUTHENTICATION_KEY = "hadoop.security.authentication";
public static final String HDFS_DEFAULT_FS_KEY = "fs.defaultFS";
private FileSystem fileSystem = null;
private JobConf conf = null;
private org.apache.hadoop.conf.Configuration hadoopConf = null;
// Kerberos
private boolean haveKerberos = false;
private String kerberosKeytabFilePath;
private String kerberosPrincipal;
public static MutablePair<Text, Boolean> transportOneRecord(
com.alibaba.datax.common.element.Record record, char fieldDelimiter, List<Configuration> columnsConfiguration, TaskPluginCollector taskPluginCollector)
{
MutablePair<List<Object>, Boolean> transportResultList = transportOneRecord(record, columnsConfiguration, taskPluginCollector);
//保存<转换后的数据,是否是脏数据>
MutablePair<Text, Boolean> transportResult = new MutablePair<>();
transportResult.setRight(false);
Text recordResult = new Text(StringUtils.join(transportResultList.getLeft(), fieldDelimiter));
transportResult.setRight(transportResultList.getRight());
transportResult.setLeft(recordResult);
return transportResult;
}
public static MutablePair<List<Object>, Boolean> transportOneRecord(
com.alibaba.datax.common.element.Record record, List<Configuration> columnsConfiguration,
TaskPluginCollector taskPluginCollector)
{
MutablePair<List<Object>, Boolean> transportResult = new MutablePair<>();
transportResult.setRight(false);
List<Object> recordList = Lists.newArrayList();
int recordLength = record.getColumnNumber();
if (0 != recordLength) {
Column column;
for (int i = 0; i < recordLength; i++) {
column = record.getColumn(i);
if (null != column.getRawData()) {
String rowData = column.getRawData().toString();
SupportHiveDataType columnType = SupportHiveDataType.valueOf(
columnsConfiguration.get(i).getString(Key.TYPE).toUpperCase());
//根据writer端类型配置做类型转换
try {
switch (columnType) {
case TINYINT:
recordList.add(Byte.valueOf(rowData));
break;
case SMALLINT:
recordList.add(Short.valueOf(rowData));
break;
case INT:
case INTEGER:
recordList.add(Integer.valueOf(rowData));
break;
case BIGINT:
recordList.add(column.asLong());
break;
case FLOAT:
recordList.add(Float.valueOf(rowData));
break;
case DOUBLE:
recordList.add(column.asDouble());
break;
case STRING:
case VARCHAR:
case CHAR:
recordList.add(column.asString());
break;
case DECIMAL:
recordList.add(HiveDecimal.create(column.asBigDecimal()));
break;
case BOOLEAN:
recordList.add(column.asBoolean());
break;
case DATE:
recordList.add(org.apache.hadoop.hive.common.type.Date.valueOf(column.asString()));
break;
case TIMESTAMP:
recordList.add(Timestamp.valueOf(column.asString()));
break;
case BINARY:
recordList.add(column.asBytes());
break;
default:
throw DataXException
.asDataXException(
HdfsWriterErrorCode.ILLEGAL_VALUE,
String.format(
"您的配置文件中的列配置信息有误. 因为DataX 不支持数据库写入这种字段类型. 字段名:[%s], 字段类型:[%s]. 请修改表中该字段的类型或者不同步该字段.",
columnsConfiguration.get(i).getString(Key.NAME),
columnsConfiguration.get(i).getString(Key.TYPE)));
}
}
catch (Exception e) {
// warn: 此处认为脏数据
e.printStackTrace();
String message = String.format(
"字段类型转换错误:你目标字段为[%s]类型,实际字段值为[%s].",
columnsConfiguration.get(i).getString(Key.TYPE), column.getRawData());
taskPluginCollector.collectDirtyRecord(record, message);
transportResult.setRight(true);
break;
}
}
else {
// warn: it's all ok if nullFormat is null
recordList.add(null);
}
}
}
transportResult.setLeft(recordList);
return transportResult;
}
public static GenericRecord transportParRecord(
com.alibaba.datax.common.element.Record record, List<Configuration> columnsConfiguration,
TaskPluginCollector taskPluginCollector, GenericRecordBuilder builder)
{
int recordLength = record.getColumnNumber();
if (0 != recordLength) {
Column column;
for (int i = 0; i < recordLength; i++) {
column = record.getColumn(i);
if (null != column.getRawData()) {
String rowData = column.getRawData().toString();
String colname = columnsConfiguration.get(i).getString("name");
String typename = columnsConfiguration.get(i).getString(Key.TYPE).toUpperCase();
if (typename.contains("DECIMAL(")) {
typename = "DECIMAL";
}
SupportHiveDataType columnType = SupportHiveDataType.valueOf(typename);
//根据writer端类型配置做类型转换
try {
switch (columnType) {
case INT:
case INTEGER:
builder.set(colname, Integer.valueOf(rowData));
break;
case LONG:
builder.set(colname, column.asLong());
break;
case FLOAT:
builder.set(colname, Float.valueOf(rowData));
break;
case DOUBLE:
builder.set(colname, column.asDouble());
break;
case STRING:
builder.set(colname, column.asString());
break;
case DECIMAL:
builder.set(colname, column.asBigDecimal());
break;
case BOOLEAN:
builder.set(colname, column.asBoolean());
break;
case BINARY:
builder.set(colname, column.asBytes());
break;
default:
throw DataXException
.asDataXException(
HdfsWriterErrorCode.ILLEGAL_VALUE,
String.format(
"您的配置文件中的列配置信息有误. 因为DataX 不支持数据库写入这种字段类型. 字段名:[%s], 字段类型:[%s]. 请修改表中该字段的类型或者不同步该字段.",
columnsConfiguration.get(i).getString(Key.NAME),
columnsConfiguration.get(i).getString(Key.TYPE)));
}
}
catch (Exception e) {
// warn: 此处认为脏数据
String message = String.format(
"字段类型转换错误:目标字段为[%s]类型,实际字段值为[%s].",
columnsConfiguration.get(i).getString(Key.TYPE), column.getRawData());
taskPluginCollector.collectDirtyRecord(record, message);
break;
}
}
}
}
return builder.build();
}
public void getFileSystem(String defaultFS, Configuration taskConfig)
{
hadoopConf = new org.apache.hadoop.conf.Configuration();
Configuration hadoopSiteParams = taskConfig.getConfiguration(Key.HADOOP_CONFIG);
JSONObject hadoopSiteParamsAsJsonObject = JSON.parseObject(taskConfig.getString(Key.HADOOP_CONFIG));
if (null != hadoopSiteParams) {
Set<String> paramKeys = hadoopSiteParams.getKeys();
for (String each : paramKeys) {
hadoopConf.set(each, hadoopSiteParamsAsJsonObject.getString(each));
}
}
hadoopConf.set(HDFS_DEFAULT_FS_KEY, defaultFS);
//是否有Kerberos认证
this.haveKerberos = taskConfig.getBool(Key.HAVE_KERBEROS, false);
if (haveKerberos) {
this.kerberosKeytabFilePath = taskConfig.getString(Key.KERBEROS_KEYTAB_FILE_PATH);
this.kerberosPrincipal = taskConfig.getString(Key.KERBEROS_PRINCIPAL);
hadoopConf.set(HADOOP_SECURITY_AUTHENTICATION_KEY, "kerberos");
}
this.kerberosAuthentication(this.kerberosPrincipal, this.kerberosKeytabFilePath);
conf = new JobConf(hadoopConf);
try {
fileSystem = FileSystem.get(conf);
}
catch (IOException e) {
String message = String.format("获取FileSystem时发生网络IO异常,请检查您的网络是否正常!HDFS地址:[message:defaultFS = %s]",
defaultFS);
LOG.error(message);
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
catch (Exception e) {
String message = String.format("获取FileSystem失败,请检查HDFS地址是否正确: [%s]",
"message:defaultFS =" + defaultFS);
LOG.error(message);
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
if (null == fileSystem) {
String message = String.format("获取FileSystem失败,请检查HDFS地址是否正确: [message:defaultFS = %s]",
defaultFS);
LOG.error(message);
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, message);
}
}
private void kerberosAuthentication(String kerberosPrincipal, String kerberosKeytabFilePath)
{
if (haveKerberos && StringUtils.isNotBlank(this.kerberosPrincipal) && StringUtils.isNotBlank(this.kerberosKeytabFilePath)) {
UserGroupInformation.setConfiguration(this.hadoopConf);
try {
UserGroupInformation.loginUserFromKeytab(kerberosPrincipal, kerberosKeytabFilePath);
}
catch (Exception e) {
String message = String.format("kerberos认证失败,请确定kerberosKeytabFilePath[%s]和kerberosPrincipal[%s]填写正确",
kerberosKeytabFilePath, kerberosPrincipal);
LOG.error(message);
throw DataXException.asDataXException(HdfsWriterErrorCode.KERBEROS_LOGIN_ERROR, e);
}
}
}
/**
* 获取指定目录先的文件列表
*
* @param dir 需要搜索的目录
* @return 拿到的是文件全路径,
* eg:hdfs://10.101.204.12:9000/user/hive/warehouse/writer.db/text/test.textfile
*/
public String[] hdfsDirList(String dir)
{
Path path = new Path(dir);
String[] files;
try {
FileStatus[] status = fileSystem.listStatus(path);
files = new String[status.length];
for (int i = 0; i < status.length; i++) {
files[i] = status[i].getPath().toString();
}
}
catch (IOException e) {
String message = String.format("获取目录[%s]文件列表时发生网络IO异常,请检查您的网络是否正常!", dir);
LOG.error(message);
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
return files;
}
/**
* 获取以指定目录下的所有fileName开头的文件
*
* @param dir 需要扫描的目录
* @param fileName String 要匹配的文件或者目录后缀,如果为空,则表示不做模式匹配
* @return Path[]
*/
public Path[] hdfsDirList(String dir, String fileName)
{
Path path = new Path(dir);
Path[] files;
try {
FileStatus[] status = fileSystem.listStatus(path);
files = new Path[status.length];
for (int i = 0; i < status.length; i++) {
files[i] = status[i].getPath();
}
}
catch (IOException e) {
String message = String.format("获取目录[%s]下文件列表时发生网络IO异常,请检查您的网络是否正常!", dir);
LOG.error(message);
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
return files;
}
public boolean isPathexists(String filePath)
{
Path path = new Path(filePath);
boolean exist;
try {
exist = fileSystem.exists(path);
}
catch (IOException e) {
String message = String.format("判断文件路径[%s]是否存在时发生网络IO异常,请检查您的网络是否正常!",
"message:filePath =" + filePath);
LOG.error(message);
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
return exist;
}
public boolean isPathDir(String filePath)
{
Path path = new Path(filePath);
boolean isDir;
try {
isDir = fileSystem.getFileStatus(path).isDirectory();
}
catch (IOException e) {
String message = String.format("判断路径[%s]是否是目录时发生网络IO异常,请检查您的网络是否正常!", filePath);
LOG.error(message);
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
return isDir;
}
/*
* 根据标志来删除特定文件
* @link(https://gitlab.ds.cfzq.com/grp_ds/datax/-/issues/8)
* delDotFile: 是否删除点(.)开头的文件, true: 表示仅删除点开头的文件, false 表示不删除点开头的文件
*
*/
public void deleteFiles(Path[] paths, boolean delDotFile)
{
List<Path> needDelPaths;
if (delDotFile) {
LOG.info("仅删除指定目录下的点(.)开头的文件或文件夹");
needDelPaths = Arrays.stream(paths).filter(x -> x.getName().startsWith(".")).collect(Collectors.toList());
}
else {
LOG.info("删除指定目录下的不以点(.)开头的文件夹或文件夹");
needDelPaths = Arrays.stream(paths).filter(x -> !x.getName().startsWith(".")).collect(Collectors.toList());
}
for (Path path : needDelPaths) {
try {
fileSystem.delete(path, true);
}
catch (IOException e) {
LOG.error("删除文件[{}]时发生IO异常,请检查您的网络是否正常!", path);
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
}
}
public void deleteFiles(Path[] paths)
{
for (Path path : paths) {
LOG.info("delete file [{}].", path);
try {
fileSystem.delete(path, true);
}
catch (IOException e) {
LOG.error("删除文件[{}]时发生IO异常,请检查您的网络是否正常!", path);
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
}
}
public void deleteDir(Path path)
{
LOG.info("start delete tmp dir [{}] .", path);
try {
if (isPathexists(path.toString())) {
fileSystem.delete(path, true);
}
}
catch (Exception e) {
LOG.error("删除临时目录[{}]时发生IO异常,请检查您的网络是否正常!", path);
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
LOG.info("finish delete tmp dir [{}] .", path);
}
public void renameFile(Set<String> tmpFiles, Set<String> endFiles)
{
Path tmpFilesParent = null;
if (tmpFiles.size() != endFiles.size()) {
String message = "临时目录下文件名个数与目标文件名个数不一致!";
LOG.error(message);
throw DataXException.asDataXException(HdfsWriterErrorCode.HDFS_RENAME_FILE_ERROR, message);
}
else {
try {
for (Iterator<String> it1 = tmpFiles.iterator(), it2 = endFiles.iterator(); it1.hasNext() && it2.hasNext(); ) {
String srcFile = it1.next();
String dstFile = it2.next();
Path srcFilePah = new Path(srcFile);
Path dstFilePah = new Path(dstFile);
if (tmpFilesParent == null) {
tmpFilesParent = srcFilePah.getParent();
}
LOG.info("start rename file [{}] to file [{}].", srcFile, dstFile);
boolean renameTag;
long fileLen = fileSystem.getFileStatus(srcFilePah).getLen();
if (fileLen > 0) {
renameTag = fileSystem.rename(srcFilePah, dstFilePah);
if (!renameTag) {
String message = String.format("重命名文件[%s]失败,请检查您的网络是否正常!", srcFile);
LOG.error(message);
throw DataXException.asDataXException(HdfsWriterErrorCode.HDFS_RENAME_FILE_ERROR, message);
}
LOG.info("finish rename file.");
}
else {
LOG.info("文件[{}]内容为空,请检查写入是否正常!", srcFile);
}
}
}
catch (Exception e) {
LOG.error("重命名文件时发生异常,请检查您的网络是否正常!");
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
}
}
//关闭FileSystem
public void closeFileSystem()
{
try {
fileSystem.close();
}
catch (IOException e) {
LOG.error("关闭FileSystem时发生IO异常,请检查您的网络是否正常!");
throw DataXException.asDataXException(HdfsWriterErrorCode.CONNECT_HDFS_IO_ERROR, e);
}
}
/**
* 写textfile类型文件
*/
public void textFileStartWrite(RecordReceiver lineReceiver, Configuration config, String fileName,
TaskPluginCollector taskPluginCollector)
{
char fieldDelimiter = config.getChar(Key.FIELD_DELIMITER);
List<Configuration> columns = config.getListConfiguration(Key.COLUMN);
String compress = config.getString(Key.COMPRESS, "NONE").toUpperCase().trim();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
String attempt = "attempt_" + dateFormat.format(new Date()) + "_0001_m_000000_0";
Path outputPath = new Path(fileName);
conf.set(JobContext.TASK_ATTEMPT_ID, attempt);
FileOutputFormat.setOutputPath(conf, outputPath);
FileOutputFormat.setWorkOutputPath(conf, outputPath);
if (!"NONE".equals(compress)) {
Class<? extends CompressionCodec> codecClass = getCompressCodec(compress);
if (null != codecClass) {
FileOutputFormat.setOutputCompressorClass(conf, codecClass);
}
}
try {
RecordWriter<NullWritable, Text> writer = new TextOutputFormat<NullWritable, Text>().getRecordWriter(fileSystem, conf, outputPath.toString(), Reporter.NULL);
com.alibaba.datax.common.element.Record record;
while ((record = lineReceiver.getFromReader()) != null) {
MutablePair<Text, Boolean> transportResult = transportOneRecord(record, fieldDelimiter, columns, taskPluginCollector);
if (Boolean.FALSE.equals(transportResult.getRight())) {
writer.write(NullWritable.get(), transportResult.getLeft());
}
}
writer.close(Reporter.NULL);
}
catch (Exception e) {
LOG.error("写文件文件[{}]时发生IO异常,请检查您的网络是否正常!", fileName);
Path path = new Path(fileName);
deleteDir(path.getParent());
throw DataXException.asDataXException(HdfsWriterErrorCode.Write_FILE_IO_ERROR, e);
}
}
// compress 已经转为大写
public Class<? extends CompressionCodec> getCompressCodec(String compress)
{
compress = compress.toUpperCase();
Class<? extends CompressionCodec> codecClass;
switch (compress) {
case "GZIP":
codecClass = org.apache.hadoop.io.compress.GzipCodec.class;
break;
case "BZIP2":
codecClass = org.apache.hadoop.io.compress.BZip2Codec.class;
break;
case "SNAPPY":
codecClass = org.apache.hadoop.io.compress.SnappyCodec.class;
break;
case "LZ4":
codecClass = org.apache.hadoop.io.compress.Lz4Codec.class;
break;
case "ZSTD":
codecClass = org.apache.hadoop.io.compress.ZStandardCodec.class;
break;
case "DEFLATE":
case "ZLIB":
codecClass = org.apache.hadoop.io.compress.DeflateCodec.class;
break;
default:
throw DataXException.asDataXException(HdfsWriterErrorCode.ILLEGAL_VALUE,
String.format("目前不支持您配置的 compress 模式 : [%s]", compress));
}
return codecClass;
}
public String getDecimalprec(String type)
{
String regEx = "[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(type);
return m.replaceAll(" ").trim().split(" ")[0];
}
public String getDecimalscale(String type)
{
String regEx = "[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(type);
return m.replaceAll(" ").trim().split(" ")[1];
}
/**
* 写Parquetfile类型文件
*/
public void parquetFileStartWrite(RecordReceiver lineReceiver, Configuration config, String fileName,
TaskPluginCollector taskPluginCollector)
{
List<Configuration> columns = config.getListConfiguration(Key.COLUMN);
String compress = config.getString(Key.COMPRESS, "UNCOMPRESSED").toUpperCase().trim();
if ("NONE".equals(compress)) {
compress = "UNCOMPRESSED";
}
// List<String> columnNames = getColumnNames(columns)
// List<ObjectInspector> columnTypeInspectors = getparColumnTypeInspectors(columns);
// StructObjectInspector inspector = ObjectInspectorFactory
// .getStandardStructObjectInspector(columnNames, columnTypeInspectors);
Path path = new Path(fileName);
String strschema = "{"
+ "\"type\": \"record\"," //Must be set as record
+ "\"name\": \"record\"," //Not used in Parquet, can put anything
+ "\"fields\": [";
for (Configuration column : columns) {
if (column.getString("type").toUpperCase().contains("DECIMAL(")) {
strschema += " {\"name\": \"" + column.getString("name")
+ "\", \"type\": {\"type\": \"fixed\", \"size\":16, \"logicalType\": \"decimal\", \"name\": \"decimal\", \"precision\": "
+ getDecimalprec(column.getString("type")) + ", \"scale\":"
+ getDecimalscale(column.getString("type")) + "}},";
}
else {
strschema += " {\"name\": \"" + column.getString("name") + "\", \"type\": \""
+ column.getString("type") + "\"},";
}
}
strschema = strschema.substring(0, strschema.length() - 1) + " ]}";
Schema.Parser parser = new Schema.Parser().setValidate(true);
Schema parSchema = parser.parse(strschema);
CompressionCodecName codecName = CompressionCodecName.fromConf(compress);
GenericData decimalSupport = new GenericData();
decimalSupport.addLogicalTypeConversion(new Conversions.DecimalConversion());
try {
ParquetWriter<GenericRecord> writer = AvroParquetWriter
.<GenericRecord>builder(path)
.withDataModel(decimalSupport)
.withCompressionCodec(codecName)
.withSchema(parSchema)
.build();
GenericRecordBuilder builder = new GenericRecordBuilder(parSchema);
com.alibaba.datax.common.element.Record record;
while ((record = lineReceiver.getFromReader()) != null) {
GenericRecord transportResult = transportParRecord(record, columns, taskPluginCollector, builder);
writer.write(transportResult);
}
writer.close();
}
catch (Exception e) {
LOG.error("写文件文件[{}]时发生IO异常,请检查您的网络是否正常!", fileName);
deleteDir(path.getParent());
throw DataXException.asDataXException(HdfsWriterErrorCode.Write_FILE_IO_ERROR, e);
}
}
private void setRow(VectorizedRowBatch batch, int row, Record record, List<Configuration> columns)
{
for (int i = 0; i < columns.size(); i++) {
Configuration eachColumnConf = columns.get(i);
SupportHiveDataType columnType = SupportHiveDataType.valueOf(eachColumnConf.getString(Key.TYPE).toUpperCase());
switch (columnType) {
case TINYINT:
case SMALLINT:
case INT:
case BIGINT:
case DATE:
case BOOLEAN:
((LongColumnVector) batch.cols[i]).vector[row] = record.getColumn(i).asLong();
break;
case FLOAT:
case DOUBLE:
((DoubleColumnVector) batch.cols[i]).vector[row] = record.getColumn(i).asDouble();
break;
case DECIMAL:
HiveDecimalWritable hdw = new HiveDecimalWritable();
hdw.set(HiveDecimal.create(record.getColumn(i).asBigDecimal()));
((DecimalColumnVector) batch.cols[i]).set(row, hdw);
break;
case TIMESTAMP:
((TimestampColumnVector) batch.cols[i]).set(row, java.sql.Timestamp.valueOf(record.getColumn(i).asString()));
break;
case STRING:
case VARCHAR:
case CHAR:
case BINARY:
byte[] buffer;
if ("DATE".equals( record.getColumn(i).getType().toString())) {
buffer = record.getColumn(i).asString().getBytes(StandardCharsets.UTF_8);
} else {
buffer = record.getColumn(i).asBytes();
}
((BytesColumnVector) batch.cols[i]).setRef(row, buffer, 0, buffer.length);
break;
default:
throw DataXException
.asDataXException(
HdfsWriterErrorCode.ILLEGAL_VALUE,
String.format(
"您的配置文件中的列配置信息有误. 因为DataX 不支持数据库写入这种字段类型. 字段名:[%s], 字段类型:[%s]. 请修改表中该字段的类型或者不同步该字段.",
eachColumnConf.getString(Key.NAME),
eachColumnConf.getString(Key.TYPE)));
}
}
}
/**
* 写orcfile类型文件
*/
public void orcFileStartWrite(RecordReceiver lineReceiver, Configuration config, String fileName,
TaskPluginCollector taskPluginCollector)
{
List<Configuration> columns = config.getListConfiguration(Key.COLUMN);
String compress = config.getString(Key.COMPRESS, "NONE").toUpperCase();
List<String> columnNames = getColumnNames(columns);
List<ObjectInspector> columnTypeInspectors = getColumnTypeInspectors(columns);
StringJoiner joiner = new StringJoiner(",");
for (int i = 0; i < columns.size(); i++) {
joiner.add(columnNames.get(i) + ":" + columnTypeInspectors.get(i).getTypeName());
}
TypeDescription schema = TypeDescription.fromString("struct<" + joiner + ">");
try (Writer writer = OrcFile.createWriter(new Path(fileName),
OrcFile.writerOptions(conf)
.setSchema(schema)
.compress(CompressionKind.valueOf(compress)))) {
Record record;
VectorizedRowBatch batch = schema.createRowBatch(1024);
while ((record = lineReceiver.getFromReader()) != null) {
int row = batch.size++;
setRow(batch, row, record, columns);
if (batch.size == batch.getMaxSize()) {
writer.addRowBatch(batch);
batch.reset();
}
}
if (batch.size != 0) {
writer.addRowBatch(batch);
batch.reset();
}
}
catch (IOException e) {
LOG.error("写文件文件[{}]时发生IO异常,请检查您的网络是否正常!", fileName);
Path path = new Path(fileName);
deleteDir(path.getParent());
throw DataXException.asDataXException(HdfsWriterErrorCode.Write_FILE_IO_ERROR, e);
}
}
public List<String> getColumnNames(List<Configuration> columns)
{
List<String> columnNames = Lists.newArrayList();
for (Configuration eachColumnConf : columns) {
columnNames.add(eachColumnConf.getString(Key.NAME));
}
return columnNames;
}
/**
* 根据writer配置的字段类型,构建inspector
*/
public List<ObjectInspector> getColumnTypeInspectors(List<Configuration> columns)
{
List<ObjectInspector> columnTypeInspectors = Lists.newArrayList();
for (Configuration eachColumnConf : columns) {
SupportHiveDataType columnType = SupportHiveDataType.valueOf(eachColumnConf.getString(Key.TYPE).toUpperCase());
ObjectInspector objectInspector;
switch (columnType) {
case TINYINT:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(Byte.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case SMALLINT:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(Short.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case INT:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(Integer.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case BIGINT:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(Long.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case FLOAT:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(Float.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case DOUBLE:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(Double.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case DECIMAL:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(HiveDecimal.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case TIMESTAMP:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(Timestamp.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case DATE:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(org.apache.hadoop.hive.common.type.Date.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case STRING:
case VARCHAR:
case CHAR:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(String.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case BOOLEAN:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(Boolean.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
case BINARY:
objectInspector = ObjectInspectorFactory.getReflectionObjectInspector(java.sql.Blob.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
break;
default:
throw DataXException
.asDataXException(
HdfsWriterErrorCode.ILLEGAL_VALUE,
String.format(
"您的配置文件中的列配置信息有误. 因为DataX 不支持数据库写入这种字段类型. 字段名:[%s], 字段类型:[%s]. 请修改表中该字段的类型或者不同步该字段.",
eachColumnConf.getString(Key.NAME),
eachColumnConf.getString(Key.TYPE)));
}
columnTypeInspectors.add(objectInspector);
}
return columnTypeInspectors;
}
} | 45.391304 | 189 | 0.561249 |
2af37c3537bce0904eea84060da7bb5e245f6ebb | 1,322 | package com.discordbot.Listener;
import com.discordbot.Discord.DiscordClient;
import com.discordbot.Discord.Sender;
import com.discordbot.Discord.UniqueIDHandler;
import com.discordbot.Embeds.FailureLogEmbed;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.guild.member.GuildMemberLeaveEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import javax.annotation.Nonnull;
import java.util.logging.Logger;
public class MemberGuildLeave extends ListenerAdapter {
private final static Logger LOGGER = Logger.getLogger(DiscordClient.class.getName());
@Override
public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) {
LOGGER.info("Member " + event.getUser().getName() + " left guild " + event.getGuild().getName());
EmbedBuilder embed = new FailureLogEmbed();
User user = event.getUser();
embed.setAuthor("Member left", user.getAvatarUrl(), user.getAvatarUrl());
embed.setDescription(user.getAsMention() + " | " + user.getAsTag());
embed.setFooter("UserID: " + user.getId() + " | " + UniqueIDHandler.getNewUUID() + " | MemberLeave");
Sender.sendToAllLogChannels(event, embed.build());
}
}
| 42.645161 | 109 | 0.744327 |
232ab5717c9aa50f4e75e52c6b097d10911ab20e | 2,330 | package com.pj.servlet;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
@WebServlet("/MenuImage")
public class MenuImage extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename;
if(request.getParameter("filename")!=null) {
filename=request.getParameter("filename");
}else if(request.getAttribute("filename")!=null) {
filename=(String) request.getAttribute("filename");
}else {
filename="19";
}//download
System.out.println(filename);
try {
Context context=new InitialContext();
DataSource ds = (DataSource)context.lookup("java:/comp/env/jdbc/servdb");
Connection conn=ds.getConnection();
PreparedStatement pstmt = conn.prepareStatement("Select img FROM [PepperNoodles].[dbo].[menu] WHERE menu_seq =?" );
pstmt.setString(1,filename);
ResultSet rs = pstmt.executeQuery();
byte[] file=null;
response.setContentType("image/*");
ServletOutputStream writer = response.getOutputStream();
if (rs.next()) {
BufferedInputStream bis = new BufferedInputStream(rs.getBinaryStream(1));
file = new byte[1024];
int length;
while ((length = bis.read(file)) != -1) {
writer.write(file);
}
bis.close();
}
rs.close();
pstmt.close();
conn.close();
writer.flush();
writer.close();
} catch (NamingException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| 32.361111 | 123 | 0.704292 |
5a9a2396d1f913a8b4682881e8ee166a21f0d11e | 5,259 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;
import javax.net.ServerSocketFactory;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class FileServer {
private final int PORT = 7777;
private final int USER_LIMIT = 100;
public static final int VALID = 0;
public static final int BAD_CREDENTIALS = 1;
public static final int NO_PERMISSION = 2;
public static final int TIME_PERMISSION = 3;
private int userCount;
private ServerSocket server;
private String[] userList = new String[100];
private String[] passwordList = new String[100];
FileServer() {
try {
this.getUsers();
this.server = ServerSocketFactory.getDefault().createServerSocket(7777);
} catch (Exception var2) {
var2.printStackTrace();
}
}
public static void main(String[] args) {
FileServer instance = new FileServer();
instance.listener();
}
public void listener() {
while(true) {
try {
Socket socket = this.server.accept();
new ConnectionHandler(this, socket);
} catch (IOException var2) {
var2.printStackTrace();
}
}
}
public void getUsers() {
File inputFile = new File("." + File.separator + "users.txt");
this.userCount = 0;
try {
boolean isUser = true;
BufferedReader input = new BufferedReader(new FileReader(inputFile));
String data;
while((data = input.readLine()) != null) {
if (isUser) {
this.userList[this.userCount] = data.toLowerCase();
isUser = false;
} else {
this.passwordList[this.userCount] = data;
isUser = true;
++this.userCount;
if (this.userCount > 100) {
break;
}
}
}
for(int i = 0; i < this.userCount; ++i) {
for(int j = i + 1; j < this.userCount; ++j) {
if (this.userList[i].compareTo(this.userList[j]) > 0) {
String username = this.userList[i];
String password = this.passwordList[i];
this.userList[i] = this.userList[j];
this.passwordList[i] = this.passwordList[j];
this.userList[j] = username;
this.passwordList[j] = password;
}
}
}
System.out.print(this.userCount + " users are allowed access to the system.\n");
} catch (Exception var9) {
var9.printStackTrace();
}
}
protected int verifyData(String username, String password, String fileName) {
int status = 1;
Calendar time = Calendar.getInstance();
long currentTime = 0L;
try {
currentTime = time.getTimeInMillis();
System.out.println("The current time is: " + currentTime);
} catch (Exception var17) {
var17.printStackTrace();
}
for(int i = 0; i < this.userCount; ++i) {
if (username.equals(this.userList[i])) {
if (password.equals(this.passwordList[i])) {
status = 2;
}
break;
}
}
if (status == 1) {
return status;
} else {
File file = new File(fileName.substring(0, fileName.length() - 4).concat(".xml"));
try {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
NodeList nodeList = doc.getElementsByTagName("user");
for(int i = 0; i < nodeList.getLength(); ++i) {
Element current = (Element)nodeList.item(i);
if (username.replace(" ", "").equals(current.getElementsByTagName("username").item(0).getFirstChild().getTextContent().replace(" ", ""))) {
long after = Long.parseLong(current.getElementsByTagName("after").item(0).getFirstChild().getTextContent());
long before = Long.parseLong(current.getElementsByTagName("before").item(0).getFirstChild().getTextContent());
if (currentTime > after && currentTime < before) {
status = 0;
} else {
status = 3;
}
break;
}
}
return status;
} catch (Exception var18) {
var18.printStackTrace();
return 1;
}
}
}
protected String getProperty(String fileName, String property) {
String output = "";
File file = new File(fileName);
try {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
Element current = (Element)doc.getElementsByTagName("properties").item(0);
current = (Element)current.getElementsByTagName(property).item(0);
output = current.getFirstChild().getTextContent();
} catch (Exception var8) {
var8.printStackTrace();
}
return output;
}
}
| 32.263804 | 154 | 0.563415 |
9cc3e3c7be2f4ac03b86ec946bab90babe85ef13 | 197 | package br.com.transmetais.dao;
import br.com.transmetais.bean.ContaCliente;
import br.com.transmetais.dao.commons.CrudDAO;
public interface ContaClienteDAO extends CrudDAO<ContaCliente>{
}
| 17.909091 | 63 | 0.807107 |
8baeeadaa8a1796fbeda7cb53c14586f7cbd0a94 | 354 | package com.beanu.l3_post.adapter.add_post;
import com.beanu.l3_post.model.bean.PostContent;
import com.yanzhenjie.album.AlbumFile;
/**
* @author lizhi
* @date 2017/11/14.
*/
public interface PictureActionCallback {
void onAddPictureBtnClick(PostContent postContent);
void onPicturePreview(PostContent postContent, AlbumFile albumFile);
}
| 22.125 | 72 | 0.779661 |
12f674f3686ba4182f6757e5f1d8d00a448cc263 | 2,016 | /*
Nominal Application
User
*/
package common.auth;
import common.NominalObject;
import common.company.Company;
import java.util.HashSet;
public class User extends NominalObject {
//Atributtes
private int id;
private HashSet<Company> companies;
private Privilege privilege;
private final String name;
private String password;
/**
*
* @param id user identificator
* @param companies companies that the user can manage
* @param name user name
* @param password password for user auth
* @param privilege user privileges
*/
public User(int id, HashSet<Company> companies, String name, String password, Privilege privilege) {
this.id = id;
this.companies = companies;
this.name = name;
this.password = password;
this.privilege = privilege;
}
public User(int id, Privilege privilege, String name, String password) {
this.id = id;
this.privilege = privilege;
this.name = name;
this.password = password;
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public User(String name, String password) {
this.name = name;
this.password = password;
}
public User(String name, String password, Privilege privilege) {
this.name = name;
this.password = password;
this.privilege = privilege;
}
// GETTERS
public int getId() {
return id;
}
public HashSet<Company> getCompanies() {
return companies;
}
public Privilege getPrivilege() {
return privilege;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setPrivilege(Privilege privilege) {
this.privilege = privilege;
}
}
| 21.677419 | 104 | 0.61756 |
1633198a6b4e3643502d63dca8fa644d962f0e8e | 7,919 | package com.jt.updatedownload.quanyan;
import android.animation.AnimatorSet;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import com.gtdev5.geetolsdk.mylibrary.beans.GetNewBean;
import com.gtdev5.geetolsdk.mylibrary.util.GTDownloadUtils;
import com.gtdev5.geetolsdk.mylibrary.util.LogUtils;
import com.gtdev5.geetolsdk.mylibrary.util.ToastUtils;
import com.gtdev5.geetolsdk.mylibrary.util.Utils;
import com.gtdev5.geetolsdk.mylibrary.widget.BaseDialog;
import com.gtdev5.geetolsdk.mylibrary.widget.NumberProgressBar;
import com.jt.updatedownload.R;
import java.io.File;
/**
* Created by zl
* 2020/05/19
* 软件下载更新弹框
*/
public class QYDownloadApkDialog extends BaseDialog {
private TextView mDownLoadText, mUpdateInfoText, mCancelText, mVersionText;
private NumberProgressBar mNumberProgressBar;
private LinearLayout llBtn,llProgressbar;
private GetNewBean mGetNewBean;
private Context mContext;
private File file;
private int currentProgress;
private String mAuthority;
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1002:
ToastUtils.showShortToast("下载完成");
if (QYDownloadApkDialog.this != null) {
QYDownloadApkDialog.this.dismiss();
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("name", "");
intent.addCategory("android.intent.category.DEFAULT");
Uri data;
if (Build.VERSION.SDK_INT >= 24) {
// 临时允许
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
data = FileProvider.getUriForFile(mContext, mAuthority, file);
} else {
data = Uri.fromFile(file);
}
intent.setDataAndType(data, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
} catch (Exception e) {
LogUtils.e("安装失败", e.toString());
if (!TextUtils.isEmpty(mGetNewBean.getDownurl())) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(mGetNewBean.getDownurl()));
mContext.startActivity(intent);
}
}
break;
case 1003:
if (mNumberProgressBar != null) {
mNumberProgressBar.setProgress(currentProgress);
int length = mNumberProgressBar.getWidth()*currentProgress/mNumberProgressBar.getMax();
}
break;
case 1004:
ToastUtils.showShortToast("下载失败,打开浏览器进行下载更新");
if (QYDownloadApkDialog.this != null) {
QYDownloadApkDialog.this.dismiss();
}
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
//解除标题导致dialog不居中的印象
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
}
public QYDownloadApkDialog(@NonNull Context context, GetNewBean bean, String authority) {
super(context);
this.mContext = context;
this.mGetNewBean = bean;
this.mAuthority = authority;
setCancelable(false);
}
@Override
protected float setWidthScale() {
return 0.9f;
}
@Override
protected AnimatorSet setEnterAnim() {
return null;
}
@Override
protected AnimatorSet setExitAnim() {
return null;
}
@Override
protected void init() {
mCancelText = findViewById(R.id.tv_cancel);
mDownLoadText = findViewById(R.id.tv_update);
mUpdateInfoText = findViewById(R.id.tv_update_info);
mVersionText = findViewById(R.id.tv_version);
mNumberProgressBar = findViewById(R.id.number_progressBar);
llBtn = findViewById(R.id.ll_btn);
llProgressbar = findViewById(R.id.ll_progressbar);
if (mGetNewBean != null) {
if (!TextUtils.isEmpty(mGetNewBean.getLog())) {
mUpdateInfoText.setText(mGetNewBean.getLog());
} else {
mUpdateInfoText.setText("多处功能优化,体验更流畅,服务更稳定,马上更新吧!");
}
if (!TextUtils.isEmpty(mGetNewBean.getVername())) {
mVersionText.setVisibility(View.VISIBLE);
mVersionText.setText(String.format("最新版本:%s",mGetNewBean.getVername()));
} else {
mVersionText.setVisibility(View.GONE);
}
} else {
mVersionText.setText("最新版本:3.0.0");
mUpdateInfoText.setText("多处功能优化,体验更流畅,服务更稳定,马上更新吧!");
}
mCancelText.setOnClickListener(v -> {
if (llBtn.getVisibility() == View.GONE ) {
ToastUtils.showShortToast("正在下载更新中,无法关闭");
} else {
dismiss();
}
});
mDownLoadText.setOnClickListener(v -> updateApp());
}
/**
* 更新应用
*/
private void updateApp() {
//检查网络是否可用
if (Utils.isNetworkAvailable(mContext)) {
llProgressbar.setVisibility(View.VISIBLE);
llBtn.setVisibility(View.GONE);
//下载更新包
GTDownloadUtils.get().download(mGetNewBean.getDownurl(), "Update", new GTDownloadUtils.OnDownloadListener() {
@Override
public void onDownloadSuccess(File files) {
//下载成功
file = files;
handler.sendEmptyMessage(1002);
}
@Override
public void onDownloading(int progress) {
//在下载
handler.sendEmptyMessage(1003);
currentProgress = progress;
}
@Override
public void onDownloadFailed() {
//下载失败
handler.sendEmptyMessage(1004);
if (!TextUtils.isEmpty(mGetNewBean.getDownurl())) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(mGetNewBean.getDownurl()));
mContext.startActivity(intent);
}
}
});
} else {
ToastUtils.showShortToast("当前网络不可用,请检查网络");
}
}
@Override
public void show() {
if (mContext != null) {
Activity activity = (Activity) mContext;
if (!activity.isFinishing()) {
super.show();
}
}
}
@Override
public void dismiss() {
if (mContext != null) {
Activity activity = (Activity) mContext;
if (!activity.isFinishing()) {
super.dismiss();
}
}
}
@Override
protected int getContentViewId() {
return R.layout.qy_dialog_download;
}
}
| 34.580786 | 121 | 0.554489 |
c158688ef7a6094fc714705aa25d352a3046c437 | 42,805 | /* LanguageTool, a natural language style checker
* Copyright (C) 2016 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.server;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.sun.net.httpserver.HttpExchange;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.language.LanguageIdentifier;
import org.languagetool.markup.AnnotatedText;
import org.languagetool.markup.AnnotatedTextBuilder;
import org.languagetool.rules.CategoryId;
import org.languagetool.rules.DictionaryMatchFilter;
import org.languagetool.rules.RemoteRule;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.bitext.BitextRule;
import org.languagetool.rules.spelling.morfologik.suggestions_ordering.SuggestionsOrdererConfig;
import org.languagetool.tools.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @since 3.4
*/
abstract class TextChecker {
private static final int PINGS_CLEAN_MILLIS = 60 * 1000; // internal pings database will be cleaned this often
private static final int PINGS_MAX_SIZE = 5000;
protected abstract void setHeaders(HttpExchange httpExchange);
protected abstract String getResponse(AnnotatedText text, Language language, DetectedLanguage lang, Language motherTongue, List<RuleMatch> matches,
List<RuleMatch> hiddenMatches, String incompleteResultReason, int compactMode);
@NotNull
protected abstract List<String> getPreferredVariants(Map<String, String> parameters);
protected abstract DetectedLanguage getLanguage(String text, Map<String, String> parameters, List<String> preferredVariants,
List<String> additionalDetectLangs, List<String> preferredLangs);
protected abstract boolean getLanguageAutoDetect(Map<String, String> parameters);
@NotNull
protected abstract List<String> getEnabledRuleIds(Map<String, String> parameters);
@NotNull
protected abstract List<String> getDisabledRuleIds(Map<String, String> parameters);
protected static final int CONTEXT_SIZE = 40; // characters
protected static final int NUM_PIPELINES_PER_SETTING = 3; // for prewarming
protected final HTTPServerConfig config;
private static final Logger logger = LoggerFactory.getLogger(TextChecker.class);
private static final String ENCODING = "UTF-8";
private static final int CACHE_STATS_PRINT = 500; // print cache stats every n cache requests
private final Map<String,Integer> languageCheckCounts = new HashMap<>();
private Queue<Runnable> workQueue;
private RequestCounter reqCounter;
// keep track of timeouts of the hidden matches server, check health periodically;
// -1 => healthy, else => check timed out at given date, check back if time difference > config.getHiddenMatchesFailTimeout()
private long lastHiddenMatchesServerTimeout;
// counter; mark as down if this reaches hidenMatchesServerFall
private long hiddenMatchesServerFailures = 0;
private final LanguageIdentifier identifier;
private final ExecutorService executorService;
private final ResultCache cache;
private final DatabaseLogger databaseLogger;
private final Long logServerId;
private final Random random = new Random();
private final Set<DatabasePingLogEntry> pings = new HashSet<>();
private long pingsCleanDateMillis = System.currentTimeMillis();
PipelinePool pipelinePool; // mocked in test -> package-private / not final
TextChecker(HTTPServerConfig config, boolean internalServer, Queue<Runnable> workQueue, RequestCounter reqCounter) {
this.config = config;
this.workQueue = workQueue;
this.reqCounter = reqCounter;
this.identifier = new LanguageIdentifier();
this.identifier.enableFasttext(config.getFasttextBinary(), config.getFasttextModel());
this.executorService = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("lt-textchecker-thread-%d").build());
this.cache = config.getCacheSize() > 0 ? new ResultCache(
config.getCacheSize(), config.getCacheTTLSeconds(), TimeUnit.SECONDS) : null;
this.databaseLogger = DatabaseLogger.getInstance();
if (databaseLogger.isLogging()) {
this.logServerId = DatabaseAccess.getInstance().getOrCreateServerId();
} else {
this.logServerId = null;
}
ServerMetricsCollector.getInstance().logHiddenServerConfiguration(config.getHiddenMatchesServer() != null);
if (cache != null) {
ServerMetricsCollector.getInstance().monitorCache("languagetool_matches_cache", cache.getMatchesCache());
ServerMetricsCollector.getInstance().monitorCache("languagetool_remote_matches_cache", cache.getRemoteMatchesCache());
ServerMetricsCollector.getInstance().monitorCache("languagetool_sentences_cache", cache.getSentenceCache());
ServerMetricsCollector.getInstance().monitorCache("languagetool_remote_matches_cache", cache.getRemoteMatchesCache());
}
pipelinePool = new PipelinePool(config, cache, internalServer);
if (config.isPipelinePrewarmingEnabled()) {
logger.info("Prewarming pipelines...");
prewarmPipelinePool();
logger.info("Prewarming finished.");
}
if (config.getAbTest() != null) {
UserConfig.enableABTests();
logger.info("A/B-Test enabled: " + config.getAbTest());
if (config.getAbTest().equals("SuggestionsOrderer")) {
SuggestionsOrdererConfig.setMLSuggestionsOrderingEnabled(true);
}
}
}
private void prewarmPipelinePool() {
// setting + number of pipelines
// typical addon settings at the moment (2018-11-05)
Map<PipelinePool.PipelineSettings, Integer> prewarmSettings = new HashMap<>();
List<Language> prewarmLanguages = Stream.of(
"de-DE", "en-US", "en-GB", "pt-BR", "ru-RU", "es", "it", "fr", "pl-PL", "uk-UA")
.map(Languages::getLanguageForShortCode)
.collect(Collectors.toList());
List<String> addonDisabledRules = Collections.singletonList("WHITESPACE_RULE");
List<JLanguageTool.Mode> addonModes = Arrays.asList(JLanguageTool.Mode.TEXTLEVEL_ONLY, JLanguageTool.Mode.ALL_BUT_TEXTLEVEL_ONLY);
UserConfig user = new UserConfig();
for (Language language : prewarmLanguages) {
for (JLanguageTool.Mode mode : addonModes) {
QueryParams params = new QueryParams(Collections.emptyList(), Collections.emptyList(), addonDisabledRules,
Collections.emptyList(), Collections.emptyList(), false, true,
false, false, false, mode, JLanguageTool.Level.DEFAULT, null);
PipelinePool.PipelineSettings settings = new PipelinePool.PipelineSettings(language, null, params, config.globalConfig, user);
prewarmSettings.put(settings, NUM_PIPELINES_PER_SETTING);
PipelinePool.PipelineSettings settingsMotherTongueEqual = new PipelinePool.PipelineSettings(language, language, params, config.globalConfig, user);
PipelinePool.PipelineSettings settingsMotherTongueEnglish = new PipelinePool.PipelineSettings(language,
Languages.getLanguageForName("English"), params, config.globalConfig, user);
prewarmSettings.put(settingsMotherTongueEqual, NUM_PIPELINES_PER_SETTING);
prewarmSettings.put(settingsMotherTongueEnglish, NUM_PIPELINES_PER_SETTING);
}
}
try {
for (Map.Entry<PipelinePool.PipelineSettings, Integer> prewarmSetting : prewarmSettings.entrySet()) {
int numPipelines = prewarmSetting.getValue();
PipelinePool.PipelineSettings setting = prewarmSetting.getKey();
// request n pipelines first, return all afterwards -> creates multiple for same setting
List<Pipeline> pipelines = new ArrayList<>();
for (int i = 0; i < numPipelines; i++) {
Pipeline p = pipelinePool.getPipeline(setting);
p.check("LanguageTool");
pipelines.add(p);
}
for (Pipeline p : pipelines) {
pipelinePool.returnPipeline(setting, p);
}
}
} catch (Exception e) {
throw new RuntimeException("Error while prewarming pipelines", e);
}
}
void shutdownNow() {
executorService.shutdownNow();
RemoteRule.shutdown();
}
void checkText(AnnotatedText aText, HttpExchange httpExchange, Map<String, String> parameters, ErrorRequestLimiter errorRequestLimiter,
String remoteAddress) throws Exception {
checkParams(parameters);
long timeStart = System.currentTimeMillis();
UserLimits limits = ServerTools.getUserLimits(parameters, config);
// logging information
String agent = parameters.get("useragent") != null ? parameters.get("useragent") : "-";
Long agentId = null, userId = null;
if (databaseLogger.isLogging()) {
DatabaseAccess db = DatabaseAccess.getInstance();
agentId = db.getOrCreateClientId(parameters.get("useragent"));
userId = limits.getPremiumUid();
}
String referrer = httpExchange.getRequestHeaders().getFirst("Referer");
String userAgent = httpExchange.getRequestHeaders().getFirst("User-Agent");
if (aText.getPlainText().length() > limits.getMaxTextLength()) {
String msg = "limit: " + limits.getMaxTextLength() + ", size: " + aText.getPlainText().length();
databaseLogger.log(new DatabaseAccessLimitLogEntry("MaxCharacterSizeExceeded", logServerId, agentId, userId, msg, referrer, userAgent));
ServerMetricsCollector.getInstance().logRequestError(ServerMetricsCollector.RequestErrorType.MAX_TEXT_SIZE);
throw new TextTooLongException("Your text exceeds the limit of " + limits.getMaxTextLength() +
" characters (it's " + aText.getPlainText().length() + " characters). Please submit a shorter text.");
}
boolean filterDictionaryMatches = "true".equals(parameters.get("filterDictionaryMatches"));
Long textSessionId = null;
try {
if (parameters.containsKey("textSessionId")) {
String textSessionIdStr = parameters.get("textSessionId");
if (textSessionIdStr.contains(":")) { // transitioning to new format used in chrome addon
// format: "{random number in 0..99999}:{unix time}"
long random, timestamp;
int sepPos = textSessionIdStr.indexOf(':');
random = Long.valueOf(textSessionIdStr.substring(0, sepPos));
timestamp = Long.valueOf(textSessionIdStr.substring(sepPos + 1));
// use random number to choose a slice in possible range of values
// then choose position in slice by timestamp
long maxRandom = 100000;
long randomSegmentSize = (Long.MAX_VALUE - maxRandom) / maxRandom;
long segmentOffset = random * randomSegmentSize;
if (timestamp > randomSegmentSize) {
logger.warn(String.format("Could not transform textSessionId '%s'", textSessionIdStr));
}
textSessionId = segmentOffset + timestamp;
} else {
textSessionId = Long.valueOf(textSessionIdStr);
}
}
} catch (NumberFormatException ex) {
logger.warn("Could not parse textSessionId '" + parameters.get("textSessionId") + "' as long: " + ex.getMessage());
}
String abTest = null;
if (agent != null && config.getAbTestClients() != null && config.getAbTestClients().matcher(agent).matches()) {
boolean testRolledOut;
// partial rollout; deterministic if textSessionId given to make testing easier
if (textSessionId != null) {
testRolledOut = textSessionId % 100 < config.getAbTestRollout();
} else {
testRolledOut = random.nextInt(100) < config.getAbTestRollout();
}
if (testRolledOut) {
abTest = config.getAbTest();
}
}
UserConfig userConfig = new UserConfig(
limits.getPremiumUid() != null ? getUserDictWords(limits.getPremiumUid()) : Collections.emptyList(),
getRuleValues(parameters), config.getMaxSpellingSuggestions(), null, null, filterDictionaryMatches,
abTest, textSessionId);
//print("Check start: " + text.length() + " chars, " + langParam);
boolean autoDetectLanguage = getLanguageAutoDetect(parameters);
List<String> preferredVariants = getPreferredVariants(parameters);
if (parameters.get("noopLanguages") != null && !autoDetectLanguage) {
ServerMetricsCollector.getInstance().logRequestError(ServerMetricsCollector.RequestErrorType.INVALID_REQUEST);
throw new IllegalArgumentException("You can specify 'noopLanguages' only when also using 'language=auto'");
}
List<String> noopLangs = parameters.get("noopLanguages") != null ?
Arrays.asList(parameters.get("noopLanguages").split(",")) : Collections.emptyList();
List<String> preferredLangs = parameters.get("preferredLanguages") != null ?
Arrays.asList(parameters.get("preferredLanguages").split(",")) : Collections.emptyList();
DetectedLanguage detLang = getLanguage(aText.getPlainText(), parameters, preferredVariants, noopLangs, preferredLangs);
Language lang = detLang.getGivenLanguage();
// == temporary counting code ======================================
/*
if (httpExchange.getRequestHeaders() != null && httpExchange.getRequestHeaders().get("Accept-Language") != null) {
List<String> langs = httpExchange.getRequestHeaders().get("Accept-Language");
if (langs.size() > 0) {
String[] split = langs.get(0).split(",");
if (split.length > 0 && detLang.getDetectedLanguage() != null && detLang.getDetectedLanguage().getShortCode().equals("en")) {
int theCount1 = StringUtils.countMatches(aText.toString(), " the ");
int theCount2 = StringUtils.countMatches(aText.toString(), "The ");
String browserLang = split[0];
System.out.println("STAT\t" + detLang.getDetectedLanguage().getShortCode() + "\t" + detLang.getDetectionConfidence() + "\t" + aText.toString().length() + "\t" + browserLang + "\t" + theCount1 + "\t" + theCount2);
}
}
}
*/
// ========================================
Integer count = languageCheckCounts.get(lang.getShortCodeWithCountryAndVariant());
if (count == null) {
count = 1;
} else {
count++;
}
//print("Starting check: " + aText.getPlainText().length() + " chars, #" + count);
String motherTongueParam = parameters.get("motherTongue");
Language motherTongue = motherTongueParam != null ? Languages.getLanguageForShortCode(motherTongueParam) : null;
boolean useEnabledOnly = "yes".equals(parameters.get("enabledOnly")) || "true".equals(parameters.get("enabledOnly"));
List<Language> altLanguages = new ArrayList<>();
if (parameters.get("altLanguages") != null) {
String[] altLangParams = parameters.get("altLanguages").split(",\\s*");
for (String langCode : altLangParams) {
Language altLang = Languages.getLanguageForShortCode(langCode);
altLanguages.add(altLang);
if (altLang.hasVariant() && !altLang.isVariant()) {
ServerMetricsCollector.getInstance().logRequestError(ServerMetricsCollector.RequestErrorType.INVALID_REQUEST);
throw new IllegalArgumentException("You specified altLanguage '" + langCode + "', but for this language you need to specify a variant, e.g. 'en-GB' instead of just 'en'");
}
}
}
List<String> enabledRules = getEnabledRuleIds(parameters);
List<String> disabledRules = getDisabledRuleIds(parameters);
List<CategoryId> enabledCategories = getCategoryIds("enabledCategories", parameters);
List<CategoryId> disabledCategories = getCategoryIds("disabledCategories", parameters);
if ((disabledRules.size() > 0 || disabledCategories.size() > 0) && useEnabledOnly) {
ServerMetricsCollector.getInstance().logRequestError(ServerMetricsCollector.RequestErrorType.INVALID_REQUEST);
throw new IllegalArgumentException("You cannot specify disabled rules or categories using enabledOnly=true");
}
if (enabledRules.isEmpty() && enabledCategories.isEmpty() && useEnabledOnly) {
ServerMetricsCollector.getInstance().logRequestError(ServerMetricsCollector.RequestErrorType.INVALID_REQUEST);
throw new IllegalArgumentException("You must specify enabled rules or categories when using enabledOnly=true");
}
boolean enableTempOffRules = "true".equals(parameters.get("enableTempOffRules"));
boolean useQuerySettings = enabledRules.size() > 0 || disabledRules.size() > 0 ||
enabledCategories.size() > 0 || disabledCategories.size() > 0 || enableTempOffRules;
boolean allowIncompleteResults = "true".equals(parameters.get("allowIncompleteResults"));
boolean enableHiddenRules = "true".equals(parameters.get("enableHiddenRules"));
JLanguageTool.Mode mode = ServerTools.getMode(parameters);
JLanguageTool.Level level = ServerTools.getLevel(parameters);
String callback = parameters.get("callback");
// allowed to log input on errors?
boolean inputLogging = !parameters.getOrDefault("inputLogging", "").equals("no");
QueryParams params = new QueryParams(altLanguages, enabledRules, disabledRules,
enabledCategories, disabledCategories, useEnabledOnly,
useQuerySettings, allowIncompleteResults, enableHiddenRules, enableTempOffRules, mode, level, callback, inputLogging);
int textSize = aText.getPlainText().length();
List<RuleMatch> ruleMatchesSoFar = Collections.synchronizedList(new ArrayList<>());
Future<List<RuleMatch>> future = executorService.submit(new Callable<List<RuleMatch>>() {
@Override
public List<RuleMatch> call() throws Exception {
// use to fake OOM in thread for testing:
/*if (Math.random() < 0.1) {
throw new OutOfMemoryError();
}*/
return getRuleMatches(aText, lang, motherTongue, parameters, params, userConfig, detLang, preferredLangs, preferredVariants, f -> ruleMatchesSoFar.add(f));
}
});
String incompleteResultReason = null;
List<RuleMatch> matches;
try {
if (limits.getMaxCheckTimeMillis() < 0) {
matches = future.get();
} else {
matches = future.get(limits.getMaxCheckTimeMillis(), TimeUnit.MILLISECONDS);
}
} catch (ExecutionException e) {
future.cancel(true);
if (ExceptionUtils.getRootCause(e) instanceof ErrorRateTooHighException) {
ServerMetricsCollector.getInstance().logRequestError(ServerMetricsCollector.RequestErrorType.TOO_MANY_ERRORS);
databaseLogger.log(new DatabaseCheckErrorLogEntry("ErrorRateTooHigh", logServerId, agentId, userId, lang, detLang.getDetectedLanguage(), textSize, "matches: " + ruleMatchesSoFar.size()));
}
if (params.allowIncompleteResults && ExceptionUtils.getRootCause(e) instanceof ErrorRateTooHighException) {
logger.warn(e.getMessage() + " - returning " + ruleMatchesSoFar.size() + " matches found so far. " +
"Detected language: " + detLang + ", " + ServerTools.getLoggingInfo(remoteAddress, null, -1, httpExchange,
parameters, System.currentTimeMillis()-timeStart, reqCounter));
matches = new ArrayList<>(ruleMatchesSoFar); // threads might still be running, so make a copy
incompleteResultReason = "Results are incomplete: " + ExceptionUtils.getRootCause(e).getMessage();
} else if (e.getCause() != null && e.getCause() instanceof OutOfMemoryError) {
throw (OutOfMemoryError)e.getCause();
} else {
throw new RuntimeException(ServerTools.cleanUserTextFromMessage(e.getMessage(), parameters) + ", detected: " + detLang, e);
}
} catch (TimeoutException e) {
boolean cancelled = future.cancel(true);
Path loadFile = Paths.get("/proc/loadavg"); // works in Linux only(?)
String loadInfo = loadFile.toFile().exists() ? Files.readAllLines(loadFile).toString() : "(unknown)";
if (errorRequestLimiter != null) {
errorRequestLimiter.logAccess(remoteAddress, httpExchange.getRequestHeaders(), parameters);
}
String message = "Text checking took longer than allowed maximum of " + limits.getMaxCheckTimeMillis() +
" milliseconds (cancelled: " + cancelled +
", lang: " + lang.getShortCodeWithCountryAndVariant() +
", detected: " + detLang +
", #" + count +
", " + aText.getPlainText().length() + " characters of text" +
", mode: " + mode.toString().toLowerCase() +
", h: " + reqCounter.getHandleCount() + ", r: " + reqCounter.getRequestCount() + ", system load: " + loadInfo + ")";
if (params.allowIncompleteResults) {
logger.info(message + " - returning " + ruleMatchesSoFar.size() + " matches found so far");
matches = new ArrayList<>(ruleMatchesSoFar); // threads might still be running, so make a copy
incompleteResultReason = "Results are incomplete: text checking took longer than allowed maximum of " +
String.format(Locale.ENGLISH, "%.2f", limits.getMaxCheckTimeMillis()/1000.0) + " seconds";
} else {
ServerMetricsCollector.getInstance().logRequestError(ServerMetricsCollector.RequestErrorType.MAX_CHECK_TIME);
databaseLogger.log(new DatabaseCheckErrorLogEntry("MaxCheckTimeExceeded",
logServerId, agentId, limits.getPremiumUid(), lang, detLang.getDetectedLanguage(), textSize, "load: "+ loadInfo));
throw new RuntimeException(message, e);
}
}
setHeaders(httpExchange);
List<RuleMatch> hiddenMatches = new ArrayList<>();
if (config.getHiddenMatchesServer() != null && params.enableHiddenRules &&
config.getHiddenMatchesLanguages().contains(lang)) {
if(config.getHiddenMatchesServerFailTimeout() > 0 && lastHiddenMatchesServerTimeout != -1 &&
System.currentTimeMillis() - lastHiddenMatchesServerTimeout < config.getHiddenMatchesServerFailTimeout()) {
ServerMetricsCollector.getInstance().logHiddenServerStatus(false);
ServerMetricsCollector.getInstance().logHiddenServerRequest(false);
logger.warn("Warn: Skipped querying hidden matches server at " +
config.getHiddenMatchesServer() + " because of recent error/timeout (timeout=" + config.getHiddenMatchesServerFailTimeout() + "ms).");
} else {
ResultExtender resultExtender = new ResultExtender(config.getHiddenMatchesServer(), config.getHiddenMatchesServerTimeout());
try {
long start = System.currentTimeMillis();
List<RemoteRuleMatch> extensionMatches = resultExtender.getExtensionMatches(aText.getPlainText(), parameters);
hiddenMatches = resultExtender.getFilteredExtensionMatches(matches, extensionMatches);
long end = System.currentTimeMillis();
logger.info("Hidden matches: " + extensionMatches.size() + " -> " + hiddenMatches.size() + " in " + (end - start) + "ms for " + lang.getShortCodeWithCountryAndVariant());
ServerMetricsCollector.getInstance().logHiddenServerStatus(true);
lastHiddenMatchesServerTimeout = -1;
hiddenMatchesServerFailures = 0;
ServerMetricsCollector.getInstance().logHiddenServerRequest(true);
} catch (Exception e) {
ServerMetricsCollector.getInstance().logHiddenServerRequest(false);
hiddenMatchesServerFailures++;
if (hiddenMatchesServerFailures >= config.getHiddenMatchesServerFall()) {
ServerMetricsCollector.getInstance().logHiddenServerStatus(false);
logger.warn("Failed to query hidden matches server at " + config.getHiddenMatchesServer() + ": " + e.getClass() + ": " + e.getMessage() + ", input was " + aText.getPlainText().length() + " characters - marked as down now");
lastHiddenMatchesServerTimeout = System.currentTimeMillis();
} else {
logger.warn("Failed to query hidden matches server at " + config.getHiddenMatchesServer() + ": " + e.getClass() + ": " + e.getMessage() + ", input was " + aText.getPlainText().length() + " characters - " + (config.getHiddenMatchesServerFall() - hiddenMatchesServerFailures) + " errors until marked as down");
}
}
}
}
int compactMode = Integer.parseInt(parameters.getOrDefault("c", "0"));
String response = getResponse(aText, lang, detLang, motherTongue, matches, hiddenMatches, incompleteResultReason, compactMode);
if (params.callback != null) {
// JSONP - still needed today for the special case of hosting your own on-premise LT without SSL
// and using it from a local MS Word (not Online Word) - issue #89 in the add-in repo:
response = params.callback + "(" + response + ");";
}
String messageSent = "sent";
String languageMessage = lang.getShortCodeWithCountryAndVariant();
try {
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes(ENCODING).length);
httpExchange.getResponseBody().write(response.getBytes(ENCODING));
ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_OK);
} catch (IOException exception) {
// the client is disconnected
messageSent = "notSent: " + exception.getMessage();
}
if (motherTongue != null) {
languageMessage += " (mother tongue: " + motherTongue.getShortCodeWithCountryAndVariant() + ")";
}
if (autoDetectLanguage) {
languageMessage += "[auto]";
}
languageCheckCounts.put(lang.getShortCodeWithCountryAndVariant(), count);
int computationTime = (int) (System.currentTimeMillis() - timeStart);
String version = parameters.get("v") != null ? ", v:" + parameters.get("v") : "";
String skipLimits = limits.getSkipLimits() ? ", skipLimits" : "";
logger.info("Check done: " + aText.getPlainText().length() + " chars, " + languageMessage + ", #" + count + ", " + referrer + ", "
+ matches.size() + " matches, "
+ computationTime + "ms, agent:" + agent + version
+ ", " + messageSent + ", q:" + (workQueue != null ? workQueue.size() : "?")
+ ", h:" + reqCounter.getHandleCount() + ", dH:" + reqCounter.getDistinctIps()
+ ", m:" + mode.toString().toLowerCase() + skipLimits);
int matchCount = matches.size();
Map<String, Integer> ruleMatchCount = new HashMap<>();
for (RuleMatch match : matches) {
String ruleId = match.getRule().getId();
ruleMatchCount.put(ruleId, ruleMatchCount.getOrDefault(ruleId, 0) + 1);
}
ServerMetricsCollector.getInstance().logCheck(
lang, computationTime, textSize, matchCount, mode);
if (!config.isSkipLoggingChecks()) {
DatabaseCheckLogEntry logEntry = new DatabaseCheckLogEntry(userId, agentId, logServerId, textSize, matchCount,
lang, detLang.getDetectedLanguage(), computationTime, textSessionId, mode.toString());
logEntry.setRuleMatches(new DatabaseRuleMatchLogEntry(
config.isSkipLoggingRuleMatches() ? Collections.emptyMap() : ruleMatchCount));
databaseLogger.log(logEntry);
}
if (databaseLogger.isLogging()) {
if (System.currentTimeMillis() - pingsCleanDateMillis > PINGS_CLEAN_MILLIS && pings.size() < PINGS_MAX_SIZE) {
logger.info("Cleaning pings DB (" + pings.size() + " items)");
pings.clear();
pingsCleanDateMillis = System.currentTimeMillis();
}
if (agentId != null && userId != null) {
DatabasePingLogEntry ping = new DatabasePingLogEntry(agentId, userId);
if (!pings.contains(ping)) {
databaseLogger.log(ping);
if (pings.size() >= PINGS_MAX_SIZE) {
// prevent pings taking up unlimited amounts of memory
logger.warn("Pings DB has reached max size: " + pings.size());
} else {
pings.add(ping);
}
}
}
}
}
private Map<String, Integer> getRuleValues(Map<String, String> parameters) {
Map<String, Integer> ruleValues = new HashMap<>();
String parameterString = parameters.get("ruleValues");
if(parameterString == null) {
return ruleValues;
}
String[] pairs = parameterString.split("[,]");
for (String pair : pairs) {
String[] ruleAndValue = pair.split("[:]");
ruleValues.put(ruleAndValue[0], Integer.parseInt(ruleAndValue[1]));
}
return ruleValues;
}
private List<String> getUserDictWords(Long userId) {
DatabaseAccess db = DatabaseAccess.getInstance();
return db.getUserDictWords(userId);
}
protected void checkParams(Map<String, String> parameters) {
if (parameters.get("text") == null && parameters.get("data") == null) {
throw new IllegalArgumentException("Missing 'text' or 'data' parameter");
}
}
private List<RuleMatch> getRuleMatches(AnnotatedText aText, Language lang,
Language motherTongue, Map<String, String> parameters,
QueryParams params, UserConfig userConfig,
DetectedLanguage detLang,
List<String> preferredLangs, List<String> preferredVariants,
RuleMatchListener listener) throws Exception {
if (cache != null && cache.requestCount() > 0 && cache.requestCount() % CACHE_STATS_PRINT == 0) {
double hitRate = cache.hitRate();
String hitPercentage = String.format(Locale.ENGLISH, "%.2f", hitRate * 100.0f);
logger.info("Cache stats: " + hitPercentage + "% hit rate");
//print("Matches : " + cache.getMatchesCache().stats().hitRate() + " hit rate");
//print("Sentences : " + cache.getSentenceCache().stats().hitRate() + " hit rate");
//print("Size : " + cache.getMatchesCache().size() + " (matches cache), " + cache.getSentenceCache().size() + " (sentence cache)");
//logger.log(new DatabaseCacheStatsLogEntry(logServerId, (float) hitRate));
}
if (parameters.get("sourceText") != null) {
if (parameters.get("sourceLanguage") == null) {
throw new IllegalArgumentException("'sourceLanguage' parameter missing - must be set when 'sourceText' is set");
}
Language sourceLanguage = Languages.getLanguageForShortCode(parameters.get("sourceLanguage"));
JLanguageTool sourceLt = new JLanguageTool(sourceLanguage);
JLanguageTool targetLt = new JLanguageTool(lang);
if (userConfig.filterDictionaryMatches()) {
targetLt.addMatchFilter(new DictionaryMatchFilter(userConfig));
}
List<BitextRule> bitextRules = Tools.getBitextRules(sourceLanguage, lang);
return Tools.checkBitext(parameters.get("sourceText"), aText.getPlainText(), sourceLt, targetLt, bitextRules);
} else {
List<RuleMatch> matches = new ArrayList<>();
if (preferredLangs.size() < 2 || parameters.get("multilingual") == null || parameters.get("multilingual").equals("false")) {
matches.addAll(getPipelineResults(aText, lang, motherTongue, params, userConfig, listener));
} else {
// support for multilingual texts:
try {
Language mainLang = getLanguageVariantForCode(detLang.getDetectedLanguage().getShortCode(), preferredVariants);
List<Language> secondLangs = new ArrayList<>();
for (String preferredLangCode : preferredLangs) {
if (!preferredLangCode.equals(mainLang.getShortCode())) {
secondLangs.add(getLanguageVariantForCode(preferredLangCode, preferredVariants));
break;
}
}
LanguageAnnotator annotator = new LanguageAnnotator();
List<FragmentWithLanguage> fragments = annotator.detectLanguages(aText.getPlainText(), mainLang, secondLangs);
List<Language> langs = new ArrayList<>();
langs.add(mainLang);
langs.addAll(secondLangs);
Map<Language, AnnotatedTextBuilder> lang2builder = getBuilderMap(fragments, new HashSet<>(langs));
for (Map.Entry<Language, AnnotatedTextBuilder> entry : lang2builder.entrySet()) {
matches.addAll(getPipelineResults(entry.getValue().build(), entry.getKey(), motherTongue, params, userConfig, listener));
}
} catch (Exception e) {
logger.error("Problem with multilingual mode (preferredLangs=" + preferredLangs+ ", preferredVariants=" + preferredVariants + "), " +
"falling back to single language.", e);
matches.addAll(getPipelineResults(aText, lang, motherTongue, params, userConfig, listener));
}
}
return matches;
}
}
private Language getLanguageVariantForCode(String langCode, List<String> preferredVariants) {
for (String preferredVariant : preferredVariants) {
if (preferredVariant.startsWith(langCode + "-")) {
return Languages.getLanguageForShortCode(preferredVariant);
}
}
return Languages.getLanguageForShortCode(langCode);
}
private List<RuleMatch> getPipelineResults(AnnotatedText aText, Language lang, Language motherTongue, QueryParams params, UserConfig userConfig, RuleMatchListener listener) throws Exception {
PipelinePool.PipelineSettings settings = null;
Pipeline lt = null;
List<RuleMatch> matches = new ArrayList<>();
try {
settings = new PipelinePool.PipelineSettings(lang, motherTongue, params, config.globalConfig, userConfig);
lt = pipelinePool.getPipeline(settings);
matches.addAll(lt.check(aText, true, JLanguageTool.ParagraphHandling.NORMAL, listener, params.mode, params.level, executorService));
} finally {
if (lt != null) {
pipelinePool.returnPipeline(settings, lt);
}
}
return matches;
}
@NotNull
private Map<Language, AnnotatedTextBuilder> getBuilderMap(List<FragmentWithLanguage> fragments, Set<Language> maybeUsedLangs) {
Map<Language, AnnotatedTextBuilder> lang2builder = new HashMap<>();
for (Language usedLang : maybeUsedLangs) {
if (!lang2builder.containsKey(usedLang)) {
lang2builder.put(usedLang, new AnnotatedTextBuilder());
}
AnnotatedTextBuilder atb = lang2builder.get(usedLang);
for (FragmentWithLanguage fragment : fragments) {
if (usedLang.getShortCodeWithCountryAndVariant().equals(fragment.getLangCode())) {
atb.addText(fragment.getFragment());
} else {
atb.addMarkup(fragment.getFragment()); // markup = ignore this text
}
}
}
return lang2builder;
}
@NotNull
private List<CategoryId> getCategoryIds(String paramName, Map<String, String> parameters) {
List<String> stringIds = getCommaSeparatedStrings(paramName, parameters);
List<CategoryId> ids = new ArrayList<>();
for (String stringId : stringIds) {
ids.add(new CategoryId(stringId));
}
return ids;
}
@NotNull
protected List<String> getCommaSeparatedStrings(String paramName, Map<String, String> parameters) {
String disabledParam = parameters.get(paramName);
List<String> result = new ArrayList<>();
if (disabledParam != null) {
result.addAll(Arrays.asList(disabledParam.split(",")));
}
return result;
}
DetectedLanguage detectLanguageOfString(String text, String fallbackLanguage, List<String> preferredVariants,
List<String> noopLangs, List<String> preferredLangs) {
DetectedLanguage detected = identifier.detectLanguage(text, noopLangs, preferredLangs);
Language lang;
if (detected == null) {
lang = Languages.getLanguageForShortCode(fallbackLanguage != null ? fallbackLanguage : "en");
} else {
lang = detected.getDetectedLanguage();
}
if (preferredVariants.size() > 0) {
for (String preferredVariant : preferredVariants) {
if (!preferredVariant.contains("-")) {
throw new IllegalArgumentException("Invalid format for 'preferredVariants', expected a dash as in 'en-GB': '" + preferredVariant + "'");
}
String preferredVariantLang = preferredVariant.split("-")[0];
if (preferredVariantLang.equals(lang.getShortCode())) {
lang = Languages.getLanguageForShortCode(preferredVariant);
if (lang == null) {
throw new IllegalArgumentException("Invalid 'preferredVariants', no such language/variant found: '" + preferredVariant + "'");
}
}
}
} else {
if (lang.getDefaultLanguageVariant() != null) {
lang = lang.getDefaultLanguageVariant();
}
}
return new DetectedLanguage(null, lang, detected != null ? detected.getDetectionConfidence() : 0f);
}
static class QueryParams {
final List<Language> altLanguages;
final List<String> enabledRules;
final List<String> disabledRules;
final List<CategoryId> enabledCategories;
final List<CategoryId> disabledCategories;
final boolean useEnabledOnly;
final boolean useQuerySettings;
final boolean allowIncompleteResults;
final boolean enableHiddenRules;
final boolean enableTempOffRules;
final JLanguageTool.Mode mode;
final JLanguageTool.Level level;
final String callback;
/** allowed to log input with stack traces to reproduce errors? */
final boolean inputLogging;
QueryParams(List<Language> altLanguages, List<String> enabledRules, List<String> disabledRules, List<CategoryId> enabledCategories, List<CategoryId> disabledCategories,
boolean useEnabledOnly, boolean useQuerySettings, boolean allowIncompleteResults, boolean enableHiddenRules, boolean enableTempOffRules, JLanguageTool.Mode mode, JLanguageTool.Level level, @Nullable String callback) {
this(altLanguages, enabledRules, disabledRules, enabledCategories, disabledCategories, useEnabledOnly, useQuerySettings, allowIncompleteResults, enableHiddenRules, enableTempOffRules, mode, level, callback, true);
}
QueryParams(List<Language> altLanguages, List<String> enabledRules, List<String> disabledRules, List<CategoryId> enabledCategories, List<CategoryId> disabledCategories,
boolean useEnabledOnly, boolean useQuerySettings, boolean allowIncompleteResults, boolean enableHiddenRules, boolean enableTempOffRules, JLanguageTool.Mode mode, JLanguageTool.Level level, @Nullable String callback, boolean inputLogging) {
this.altLanguages = Objects.requireNonNull(altLanguages);
this.enabledRules = enabledRules;
this.disabledRules = disabledRules;
this.enabledCategories = enabledCategories;
this.disabledCategories = disabledCategories;
this.useEnabledOnly = useEnabledOnly;
this.useQuerySettings = useQuerySettings;
this.allowIncompleteResults = allowIncompleteResults;
this.enableHiddenRules = enableHiddenRules;
this.enableTempOffRules = enableTempOffRules;
this.mode = Objects.requireNonNull(mode);
this.level = Objects.requireNonNull(level);
if (callback != null && !callback.matches("[a-zA-Z]+")) {
throw new IllegalArgumentException("'callback' value must match [a-zA-Z]+: '" + callback + "'");
}
this.callback = callback;
this.inputLogging = inputLogging;
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(altLanguages)
.append(enabledRules)
.append(disabledRules)
.append(enabledCategories)
.append(disabledCategories)
.append(useEnabledOnly)
.append(useQuerySettings)
.append(allowIncompleteResults)
.append(enableHiddenRules)
.append(enableTempOffRules)
.append(mode)
.append(level)
.append(callback)
.append(inputLogging)
.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || getClass() != obj.getClass()) {
return false;
}
QueryParams other = (QueryParams) obj;
return new EqualsBuilder()
.append(altLanguages, other.altLanguages)
.append(enabledRules, other.enabledRules)
.append(disabledRules, other.disabledRules)
.append(enabledCategories, other.enabledCategories)
.append(disabledCategories, other.disabledCategories)
.append(useEnabledOnly, other.useEnabledOnly)
.append(useQuerySettings, other.useQuerySettings)
.append(allowIncompleteResults, other.allowIncompleteResults)
.append(enableHiddenRules, other.enableHiddenRules)
.append(enableTempOffRules, other.enableTempOffRules)
.append(mode, other.mode)
.append(level, other.level)
.append(callback, other.callback)
.append(inputLogging, other.inputLogging)
.isEquals();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("altLanguages", altLanguages)
.append("enabledRules", enabledRules)
.append("disabledRules", disabledRules)
.append("enabledCategories", enabledCategories)
.append("disabledCategories", disabledCategories)
.append("useEnabledOnly", useEnabledOnly)
.append("useQuerySettings", useQuerySettings)
.append("allowIncompleteResults", allowIncompleteResults)
.append("enableHiddenRules", enableHiddenRules)
.append("enableTempOffRules", enableTempOffRules)
.append("mode", mode)
.append("level", level)
.append("callback", callback)
.append("inputLogging", inputLogging)
.build();
}
}
}
| 52.392901 | 320 | 0.692069 |
8db26c044c9ac2b5b907b99a9ca6073ac3e4379c | 1,609 | package cn.wz.algorithm.algs4; /*************************************************************************
* Compilation: javac DirectedEdge.java
* Execution: java DirectedEdge
*
* Immutable weighted directed edge.
*
*************************************************************************/
import cn.wz.algorithm.stdlib.StdOut;
/**
* The <tt>DirectedEdge</tt> class represents a weighted edge in an directed graph.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*/
public class DirectedEdge {
private final int v;
private final int w;
private final double weight;
/**
* Create a directed edge from v to w with given weight.
*/
public DirectedEdge(int v, int w, double weight) {
this.v = v;
this.w = w;
this.weight = weight;
}
/**
* Return the vertex where this edge begins.
*/
public int from() {
return v;
}
/**
* Return the vertex where this edge ends.
*/
public int to() {
return w;
}
/**
* Return the weight of this edge.
*/
public double weight() { return weight; }
/**
* Return a string representation of this edge.
*/
public String toString() {
return v + "->" + w + " " + String.format("%5.2f", weight);
}
/**
* Test client.
*/
public static void main(String[] args) {
DirectedEdge e = new DirectedEdge(12, 23, 3.14);
StdOut.println(e);
}
}
| 24.378788 | 105 | 0.530143 |
afecfff147675c632414a45e52813b785b7257f3 | 514 | package io.undertow.servlet.test.wrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* @author Stuart Douglas
*/
public class StandardResponseWrapper extends HttpServletResponseWrapper {
/**
* Constructs a response adaptor wrapping the given response.
*
* @throws IllegalArgumentException if the response is null
*/
public StandardResponseWrapper(final HttpServletResponse response) {
super(response);
}
}
| 24.47619 | 73 | 0.745136 |
180b6fc6b25d6b215d1e605430d9eca610e48262 | 320 | package org.bandofhawk.ntier.sample.service.model;
public class HelloWorldServiceResponseEntity
{
private String welcomeMessage;
public String getWelcomeMessage()
{
return welcomeMessage;
}
public void setWelcomeMessage(String welcomeMessage)
{
this.welcomeMessage = welcomeMessage;
}
}
| 18.823529 | 56 | 0.75 |
6631224fe6b3b6974087be72ace7adc6e1ade0e5 | 250 | //skip compare content
//CONF: lombok.Getter.flagUsage = WARNING
//CONF: lombok.experimental.flagUsage = ERROR
public class FlagUsages {
@lombok.Getter String x;
@lombok.experimental.Wither String z;
public FlagUsages(String x, String y) {
}
}
| 20.833333 | 45 | 0.748 |
86fff527584caaae22183e53522f47348f6d1680 | 372 | package com.open9527.annotation.layout;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author open_9527
* Create at 2021/2/4
**/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ContentView {
int value();
}
| 19.578947 | 44 | 0.768817 |
0bda793c06d8f9fafe333112d5939080d827c13a | 521 | package cn.test10.cc;
import java.util.Scanner;
public class J1048 {
public static void main(String[] args) {
Scanner cn = new Scanner(System.in);
int M = cn.nextInt();
while(M--!=0){
int a = cn.nextInt();
int b = cn.nextInt();
int sa=0;
int sb=0;
for(int i=1;i<a;i++){
if(a%i==0){
sa+=i;
}
}
for(int i=1;i<b;i++){
if(b%i==0){
sb+=i;
}
}
if(sa==b&&sb==a){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
cn.close();
}
}
| 15.323529 | 41 | 0.504798 |
b1e828e708aff83e16ea76d66790e0a49419b4ef | 4,801 | /*
* Copyright (c) 2013-2016, EMC Corporation.
* 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.
* + The name of EMC Corporation may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.emc.atmos.api.jersey.provider;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/**
* Base class to disable chunked encoding in requests by always specifying an accurate byte count in getSize().
* Subclasses should provide a default constructor, which calls super() with an instance of the underlying writer
* implementation to be wrapped.
* <p/>
* XXX: this is inefficient and should be replaced by a different mechanism. However, it is the simplest solution to
* the apache client's insistence on using chunked encoding for all requests with a size of -1 and Jersey's insistence
* on returning -1 from all message body providers (as well as not allowing users to override the content-length
* header).
*/
public class MeasuredMessageBodyWriter<T> implements MessageBodyWriter<T> {
protected MessageBodyWriter<T> wrapped;
private IOException delayedIOException;
private WebApplicationException delayedWebAppException;
public MeasuredMessageBodyWriter( MessageBodyWriter<T> wrapped ) {
this.wrapped = wrapped;
}
@Override
public boolean isWriteable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ) {
return wrapped.isWriteable( type, genericType, annotations, mediaType );
}
@Override
public void writeTo( T t,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream ) throws IOException, WebApplicationException {
if ( delayedIOException != null ) throw delayedIOException;
if ( delayedWebAppException != null ) throw delayedWebAppException;
entityStream.write( getBuffer( t, type, genericType, annotations, mediaType, httpHeaders ) );
}
@Override
public long getSize( T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ) {
try {
return getBuffer( t, type, genericType, annotations, mediaType, null ).length;
} catch ( IOException e ) {
delayedIOException = e;
} catch ( WebApplicationException e ) {
delayedWebAppException = e;
}
return -1;
}
protected synchronized byte[] getBuffer( T t,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders )
throws IOException, WebApplicationException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wrapped.writeTo( t, type, genericType, annotations, mediaType, httpHeaders, baos );
return baos.toByteArray();
}
}
| 48.01 | 118 | 0.687149 |
8ee491ee09dc854b1b2d2268e51ef123d793104a | 209 | package com.njackson.utils.time;
import java.util.Date;
/**
* Created by njackson on 17/01/15.
*/
public interface ITime {
public Date getCurrentDate();
public long getCurrentTimeMilliseconds();
}
| 17.416667 | 45 | 0.717703 |
b5105ef81ef97d6fe444ea2d4b4e053918472502 | 2,700 | package org.deeplearning4j.hadoop.nlp.text;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.deeplearning4j.text.sentenceiterator.SentenceIterator;
import org.deeplearning4j.text.sentenceiterator.SentencePreProcessor;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Hdfs style sentence iterator. Provides base cases for iterating over files
* and the baseline sentence iterator interface.
*
* @author Adam Gibson
*/
public abstract class ConfigurableSentenceIterator implements SentenceIterator {
protected Configuration conf;
protected FileSystem fs;
protected String rootPath;
protected Path rootFilePath;
protected Iterator<Path> paths;
protected SentencePreProcessor preProcessor;
public final static String ROOT_PATH = "org.depelearning4j.hadoop.nlp.rootPath";
public ConfigurableSentenceIterator(Configuration conf) throws IOException {
this.conf = conf;
rootPath = conf.get(ROOT_PATH);
fs = FileSystem.get(conf);
if(rootPath == null)
throw new IllegalArgumentException("Unable to create iterator from un specified file path");
rootFilePath = new Path(rootPath);
List<Path> paths = new ArrayList<>();
find(paths,rootFilePath);
this.paths = paths.iterator();
}
private void find(List<Path> paths,Path currentFile) throws IOException {
if(fs.isDirectory(currentFile)) {
FileStatus[] statuses = fs.listStatus(currentFile);
for(FileStatus status : statuses)
find(paths,status.getPath());
}
else
paths.add(currentFile);
}
@Override
public String nextSentence() {
Path next = paths.next();
try {
InputStream open = fs.open(next);
String read = new String(IOUtils.toByteArray(open));
open.close();
return read;
}catch(Exception e) {
}
return null;
}
@Override
public boolean hasNext() {
return paths.hasNext();
}
@Override
public void finish() {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public SentencePreProcessor getPreProcessor() {
return preProcessor;
}
@Override
public void setPreProcessor(SentencePreProcessor preProcessor) {
this.preProcessor = preProcessor;
}
}
| 26.732673 | 104 | 0.663704 |
24c7130c4eca998ae378325916d9afc6104522cf | 5,264 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2019 by Hitachi Vantara : http://www.pentaho.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 org.pentaho.di.www;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.w3c.dom.Node;
/**
* @author Tatsiana_Kasiankova
*
*/
public class SslConfiguration {
private static final Class<?> PKG = SslConfiguration.class; // for i18n purposes, needed by Translator2!!
public static final String XML_TAG = "sslConfig";
private static final String XML_TAG_KEY_STORE = "keyStore";
private static final String XML_TAG_KEY_STORE_TYPE = "keyStoreType";
@SuppressWarnings( "squid:S2068" ) private static final String XML_TAG_KEY_PASSWORD = "keyPassword";
@SuppressWarnings( "squid:S2068" ) private static final String XML_TAG_KEY_STORE_PASSWORD = "keyStorePassword";
private static final String EMPTY = "empty";
private static final String NULL = "null";
private String keyStoreType = "JKS";
private String keyStore;
private String keyStorePassword;
private String keyPassword;
public SslConfiguration( Node sslConfigNode ) {
super();
setKeyStore( XMLHandler.getTagValue( sslConfigNode, XML_TAG_KEY_STORE ) );
setKeyStorePassword( Encr.decryptPasswordOptionallyEncrypted( XMLHandler.getTagValue( sslConfigNode,
XML_TAG_KEY_STORE_PASSWORD ) ) );
setKeyPassword( Encr.decryptPasswordOptionallyEncrypted( XMLHandler.getTagValue( sslConfigNode,
XML_TAG_KEY_PASSWORD ) ) );
setKeyStoreType( XMLHandler.getTagValue( sslConfigNode, XML_TAG_KEY_STORE_TYPE ) );
}
/**
* @return the keyStoreType
*/
public String getKeyStoreType() {
return keyStoreType;
}
/**
* @param keyStoreType
* the keyStoreType to set
*/
public void setKeyStoreType( String keyStoreType ) {
if ( keyStoreType != null ) {
this.keyStoreType = keyStoreType;
}
}
/**
* @return the keyStorePath
*/
public String getKeyStore() {
return keyStore;
}
/**
* @param keyStorePath
* the keyStorePath to set
*/
public void setKeyStore( String keyStore ) {
Validate.notNull( keyStore, BaseMessages.getString( PKG, "WebServer.Error.IllegalSslParameter", XML_TAG_KEY_STORE,
NULL ) );
Validate.notEmpty( keyStore, BaseMessages.getString( PKG, "WebServer.Error.IllegalSslParameter", XML_TAG_KEY_STORE,
EMPTY ) );
this.keyStore = keyStore;
}
/**
* @return the keyStorePassword
*/
public String getKeyStorePassword() {
return keyStorePassword;
}
/**
* @param keyStorePassword
* the keyStorePassword to set
*/
public void setKeyStorePassword( String keyStorePassword ) {
Validate.notNull( keyStorePassword, BaseMessages.getString( PKG, "WebServer.Error.IllegalSslParameter",
XML_TAG_KEY_STORE_PASSWORD, NULL ) );
Validate.notEmpty( keyStorePassword, BaseMessages.getString( PKG, "WebServer.Error.IllegalSslParameter",
XML_TAG_KEY_STORE_PASSWORD, EMPTY ) );
this.keyStorePassword = keyStorePassword;
}
/**
* @return the keyPassword
*/
public String getKeyPassword() {
return ( this.keyPassword != null ) ? this.keyPassword : getKeyStorePassword();
}
/**
* @param keyPassword
* the keyPassword to set
*/
public void setKeyPassword( String keyPassword ) {
this.keyPassword = keyPassword;
}
public String getXML() {
StringBuilder xml = new StringBuilder();
xml.append( " " ).append( XMLHandler.openTag( XML_TAG ) ).append( Const.CR );
addXmlValue( xml, XML_TAG_KEY_STORE, keyStore );
addXmlValue( xml, XML_TAG_KEY_STORE_PASSWORD, encrypt( keyStorePassword ) );
addXmlValue( xml, XML_TAG_KEY_PASSWORD, encrypt( keyPassword ) );
xml.append( " " ).append( XMLHandler.closeTag( XML_TAG ) ).append( Const.CR );
return xml.toString();
}
private static void addXmlValue( StringBuilder xml, String key, String value ) {
if ( !StringUtils.isBlank( value ) ) {
xml.append( " " ).append( XMLHandler.addTagValue( key, value, false ) );
}
}
private static String encrypt( String value ) {
if ( !StringUtils.isBlank( value ) ) {
return Encr.encryptPasswordIfNotUsingVariables( value );
}
return null;
}
}
| 32.097561 | 119 | 0.672302 |
8742f164e77a1096d6bc08b9db32f8af4f057a30 | 506 | package ie.dit;
import processing.core.PApplet;
public class class_work extends PApplet
{
public void settings()
{
size(500, 500);
}
public void setup() {
}
public void draw() {
background(255,0,0);
noStroke();
fill(255,255,51);
ellipse(250,290,400,400);
fill(0,255,255);
triangle(250,50,50,450,450,450);
fill(128,128,128);
ellipse(250,250,195,100);
fill(0,0,0);
ellipse(250,250,80,80);
}
} | 15.8125 | 40 | 0.545455 |
507537bfd78bc58526d0f7144e2654b533c4d021 | 11,235 | package us.ihmc.humanoidBehaviors.behaviors.examples;
import java.util.Random;
import javax.vecmath.Point3d;
import javax.vecmath.Quat4d;
import us.ihmc.communication.packets.TextToSpeechPacket;
import us.ihmc.humanoidBehaviors.behaviors.complexBehaviors.ResetRobotBehavior;
import us.ihmc.humanoidBehaviors.behaviors.examples.ExampleComplexBehaviorStateMachine.ExampleStates;
import us.ihmc.humanoidBehaviors.behaviors.primitives.AtlasPrimitiveActions;
import us.ihmc.humanoidBehaviors.behaviors.simpleBehaviors.BehaviorAction;
import us.ihmc.humanoidBehaviors.communication.CommunicationBridge;
import us.ihmc.humanoidBehaviors.stateMachine.StateMachineBehavior;
import us.ihmc.humanoidRobotics.communication.packets.TrajectoryPoint1DMessage;
import us.ihmc.humanoidRobotics.communication.packets.dataobjects.HandConfiguration;
import us.ihmc.humanoidRobotics.communication.packets.manipulation.ArmTrajectoryMessage;
import us.ihmc.humanoidRobotics.communication.packets.manipulation.HandDesiredConfigurationMessage;
import us.ihmc.humanoidRobotics.communication.packets.manipulation.HandTrajectoryMessage;
import us.ihmc.humanoidRobotics.communication.packets.manipulation.OneDoFJointTrajectoryMessage;
import us.ihmc.humanoidRobotics.communication.packets.sensing.DepthDataStateCommand.LidarState;
import us.ihmc.humanoidRobotics.communication.packets.walking.GoHomeMessage;
import us.ihmc.humanoidRobotics.communication.packets.walking.GoHomeMessage.BodyPart;
import us.ihmc.robotics.dataStructures.listener.VariableChangedListener;
import us.ihmc.robotics.dataStructures.variable.DoubleYoVariable;
import us.ihmc.robotics.dataStructures.variable.YoVariable;
import us.ihmc.robotics.geometry.FrameOrientation;
import us.ihmc.robotics.geometry.FramePoint;
import us.ihmc.robotics.geometry.FramePoint2d;
import us.ihmc.robotics.geometry.FramePose;
import us.ihmc.robotics.referenceFrames.ReferenceFrame;
import us.ihmc.robotics.robotSide.RobotSide;
import us.ihmc.robotics.robotSide.SideDependentList;
import us.ihmc.simulationconstructionset.util.simulationRunner.BlockingSimulationRunner.SimulationExceededMaximumTimeException;
public class ExampleComplexBehaviorStateMachine extends StateMachineBehavior<ExampleStates>
{
public enum ExampleStates
{
ENABLE_LIDAR, SETUP_ROBOT_PARALLEL_STATEMACHINE_EXAMPLE, RESET_ROBOT_PIPELINE_EXAMPLE, GET_LIDAR, GET_VIDEO, GET_USER_VALIDATION, WHOLEBODY_EXAMPLE,
}
CommunicationBridge coactiveBehaviorsNetworkManager;
private final AtlasPrimitiveActions atlasPrimitiveActions;
private final GetLidarScanExampleBehavior getLidarScanExampleBehavior;
private final GetVideoPacketExampleBehavior getVideoPacketExampleBehavior;
private final GetUserValidationBehavior userValidationExampleBehavior;
private final SimpleArmMotionBehavior simpleArmMotionBehavior;
private final ResetRobotBehavior resetRobotBehavior;
private final ReferenceFrame midZupFrame;
public ExampleComplexBehaviorStateMachine(CommunicationBridge communicationBridge, DoubleYoVariable yoTime, AtlasPrimitiveActions atlasPrimitiveActions)
{
super("ExampleStateMachine", ExampleStates.class, yoTime, communicationBridge);
midZupFrame = atlasPrimitiveActions.referenceFrames.getMidFeetZUpFrame();
coactiveBehaviorsNetworkManager = communicationBridge;
coactiveBehaviorsNetworkManager.registerYovaribleForAutoSendToUI(statemachine.getStateYoVariable());
this.atlasPrimitiveActions = atlasPrimitiveActions;
//create your behaviors
getLidarScanExampleBehavior = new GetLidarScanExampleBehavior(communicationBridge);
getVideoPacketExampleBehavior = new GetVideoPacketExampleBehavior(communicationBridge);
userValidationExampleBehavior = new GetUserValidationBehavior(communicationBridge);
resetRobotBehavior = new ResetRobotBehavior(communicationBridge, yoTime);
simpleArmMotionBehavior = new SimpleArmMotionBehavior(yoTime, atlasPrimitiveActions.referenceFrames, communicationBridge, atlasPrimitiveActions);
setupStateMachine();
statemachine.getStateYoVariable().addVariableChangedListener(new VariableChangedListener()
{
@Override
public void variableChanged(YoVariable<?> v)
{
System.out.println("ExampleComplexBehaviorStateMachine: Changing state to " + statemachine.getCurrentState());
}
});
}
@Override
public void onBehaviorEntered()
{
TextToSpeechPacket p1 = new TextToSpeechPacket("Starting Example Behavior");
sendPacket(p1);
super.onBehaviorEntered();
}
private void setupStateMachine()
{
//TODO setup search for ball behavior
BehaviorAction<ExampleStates> enableLidar = new BehaviorAction<ExampleStates>(ExampleStates.ENABLE_LIDAR, atlasPrimitiveActions.enableLidarBehavior)
{
@Override
protected void setBehaviorInput()
{
TextToSpeechPacket p1 = new TextToSpeechPacket("Enabling Lidar");
sendPacket(p1);
atlasPrimitiveActions.enableLidarBehavior.setLidarState(LidarState.ENABLE);
}
};
BehaviorAction<ExampleStates> resetRobot = new BehaviorAction<ExampleStates>(ExampleStates.RESET_ROBOT_PIPELINE_EXAMPLE, resetRobotBehavior)
{
@Override
protected void setBehaviorInput()
{
TextToSpeechPacket p1 = new TextToSpeechPacket("Resetting Robot");
sendPacket(p1);
super.setBehaviorInput();
}
};
BehaviorAction<ExampleStates> setupRobot = new BehaviorAction<ExampleStates>(ExampleStates.SETUP_ROBOT_PARALLEL_STATEMACHINE_EXAMPLE,
simpleArmMotionBehavior)
{
@Override
protected void setBehaviorInput()
{
TextToSpeechPacket p1 = new TextToSpeechPacket("Setting Up Robot Pose");
sendPacket(p1);
super.setBehaviorInput();
}
};
// BehaviorAction<ExampleStates> setupRobot = new BehaviorAction<ExampleStates>(ExampleStates.SETUP_ROBOT_PARALLEL_STATEMACHINE_EXAMPLE,
// atlasPrimitiveActions.rightArmTrajectoryBehavior, atlasPrimitiveActions.leftHandTrajectoryBehavior,
// atlasPrimitiveActions.leftHandDesiredConfigurationBehavior)
// {
// @Override
// protected void setBehaviorInput()
// {
//
// TextToSpeechPacket p1 = new TextToSpeechPacket("Setting Up Robot Pose");
// sendPacket(p1);
//
// double[] armConfig = new double[] {-0.5067668142160446, -0.3659876546358431, 1.7973796317575155, -1.2398714600960365, -0.005510224629709242,
// 0.6123343067479899, 0.12524505635696856};
//
// ArmTrajectoryMessage armTrajectoryMessage = new ArmTrajectoryMessage();
// armTrajectoryMessage.jointTrajectoryMessages = new OneDoFJointTrajectoryMessage[armConfig.length];
// armTrajectoryMessage.robotSide = RobotSide.RIGHT;
//
// for (int i = 0; i < armConfig.length; i++)
// {
// TrajectoryPoint1DMessage trajectoryPoint = new TrajectoryPoint1DMessage();
// trajectoryPoint.position = armConfig[i];
// trajectoryPoint.time = 1.0;
// OneDoFJointTrajectoryMessage jointTrajectory = new OneDoFJointTrajectoryMessage();
// jointTrajectory.trajectoryPoints = new TrajectoryPoint1DMessage[] {trajectoryPoint};
// armTrajectoryMessage.jointTrajectoryMessages[i] = jointTrajectory;
// }
//
// atlasPrimitiveActions.rightArmTrajectoryBehavior.setInput(armTrajectoryMessage);
//
// FramePoint point1 = new FramePoint(ReferenceFrame.getWorldFrame(), .5, .5, 1);
// point1.changeFrame(ReferenceFrame.getWorldFrame());
// FrameOrientation orient = new FrameOrientation(ReferenceFrame.getWorldFrame(),1.5708, 1.5708, -3.1415);
// orient.changeFrame(ReferenceFrame.getWorldFrame());
//
// FramePose pose = new FramePose(point1, orient);
//
// HandTrajectoryMessage handmessage = new HandTrajectoryMessage(RobotSide.LEFT, 2, pose.getFramePointCopy().getPoint(),pose.getFrameOrientationCopy().getQuaternion());
//
// atlasPrimitiveActions.leftHandTrajectoryBehavior.setInput(handmessage);
//
// atlasPrimitiveActions.leftHandDesiredConfigurationBehavior.setInput(new HandDesiredConfigurationMessage(RobotSide.LEFT, HandConfiguration.CLOSE));
// }
// };
BehaviorAction<ExampleStates> wholeBodyExample = new BehaviorAction<ExampleStates>(ExampleStates.WHOLEBODY_EXAMPLE,
atlasPrimitiveActions.wholeBodyBehavior)
{
@Override
protected void setBehaviorInput()
{
TextToSpeechPacket p1 = new TextToSpeechPacket("Doing Whole Body Behavior");
sendPacket(p1);
FramePoint point = new FramePoint(midZupFrame, 0.2, 0.2, 0.3);
point.changeFrame(ReferenceFrame.getWorldFrame());
//the point in the world you want to move the hand to.
//i set this high so that more solutions are accepted
atlasPrimitiveActions.wholeBodyBehavior.setSolutionQualityThreshold(2.01);
//how fast you want the action to be
atlasPrimitiveActions.wholeBodyBehavior.setTrajectoryTime(3);
FrameOrientation tmpOr = new FrameOrientation(point.getReferenceFrame(), Math.toRadians(45), Math.toRadians(90), 0);
atlasPrimitiveActions.wholeBodyBehavior.setDesiredHandPose(RobotSide.LEFT, point, tmpOr);
}
};
BehaviorAction<ExampleStates> getLidar = new BehaviorAction<ExampleStates>(ExampleStates.GET_LIDAR, getLidarScanExampleBehavior);
BehaviorAction<ExampleStates> getVideo = new BehaviorAction<ExampleStates>(ExampleStates.GET_VIDEO, getVideoPacketExampleBehavior);
BehaviorAction<ExampleStates> getUserValidation = new BehaviorAction<ExampleStates>(ExampleStates.GET_USER_VALIDATION, userValidationExampleBehavior);
//setup the state machine
statemachine.addStateWithDoneTransition(setupRobot, ExampleStates.RESET_ROBOT_PIPELINE_EXAMPLE);
statemachine.addStateWithDoneTransition(resetRobot, ExampleStates.ENABLE_LIDAR);
statemachine.addStateWithDoneTransition(enableLidar, ExampleStates.GET_LIDAR);
statemachine.addStateWithDoneTransition(getLidar, ExampleStates.GET_VIDEO);
statemachine.addStateWithDoneTransition(getVideo, ExampleStates.WHOLEBODY_EXAMPLE);
statemachine.addStateWithDoneTransition(wholeBodyExample, ExampleStates.GET_USER_VALIDATION);
statemachine.addState(getUserValidation);
//set the starting state
statemachine.setStartState(ExampleStates.SETUP_ROBOT_PARALLEL_STATEMACHINE_EXAMPLE);
}
@Override
public void onBehaviorExited()
{
System.out.println("IM ALL DONE");
}
}
| 48.426724 | 185 | 0.737873 |
2723564e016eed0ae2f18d8f15bc558c132b587e | 2,119 | /*
* Copyright 2015 Zack Hoffmann <[email protected]>.
*
* 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.diamondboot.core;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author Zack Hoffmann <[email protected]>
*/
class DiamondBootConfig {
public static DiamondBootConfig getDefaultConfig() {
DiamondBootConfig def = new DiamondBootConfig();
def.versions.dir = "mc-versions";
def.instances.dir = "mc-instances";
def.instances.defaults.initialMemory = "1024M";
def.instances.defaults.maximumMemory = "1024M";
def.instances.defaults.version = "RECENT";
def.instances.startOnLaunch = Arrays.asList();
def.webServer.hostname = "localhost";
def.webServer.port = 8080;
return def;
}
public static class Versions {
public String dir;
}
public static class Instances {
public static class Defaults {
public String initialMemory;
public String maximumMemory;
public String version;
}
public Defaults defaults = new Defaults();
public String dir;
public List<String> startOnLaunch = ImmutableList.of();
}
public static class WebServer {
public String hostname;
public int port;
}
public Versions versions = new Versions();
public Instances instances = new Instances();
public WebServer webServer = new WebServer();
}
| 30.710145 | 76 | 0.654082 |
eeebc4cd7b797bb5738178d9cc001d65a1d8cb1a | 3,329 | package com.spring.boot.microservice;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.URL;
/**
* Janelle Baetiong (300966120) and Sadia Rashid (300963357)
* COMP303 - 001 - Lab Assignment#4
*/
//Entity and Table for Org
@Entity
@Table(name="organization")
public class Organization {
// Properties of Org
@Id
@GeneratedValue (strategy = GenerationType.AUTO) // Primary key auto-generated
@Column(name="orgid")
private int orgId;
@NotNull(message="Please add organization name.") // validation
@NotEmpty (message = "Please add organization name.") // validation
@Column(name="orgname")
private String orgName;
@NotNull
@NotEmpty(message="Please add address.") // validation
@Length (min=10,max=100,message = "Address should be between 10-100 characters.") // validation
@Column(name="address")
private String address;
@NotNull
@NotNull(message="Please add postal code.") // validation
@Pattern(regexp="^(?!.*[DFIOQU])[A-VXY][0-9][A-Z]●?[0-9][A-Z][0-9]$", message ="Postal code is invalid.") // validation
@Column(name="postalcode")
private String postalCode;
@NotNull
@NotEmpty(message="Please add phone number.") // validation
@Pattern(regexp="^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$", message="Phone number is invalid") // validation
@Column(name="phoneno")
private String phoneNo;
@NotNull(message="Please add email.")
@NotEmpty(message="Please add email.")// validation
@Pattern(regexp="^[\\w-\\+]+(\\.[\\w]+)*@[\\w-]+(\\.[\\w]+)*(\\.[a-z]{2,})$",
message="{invalid.email}") // validation
@Column(name="email")
private String email;
@URL // validation
@Column(name="website")
private String website;
// constructors
public Organization() {
super();
}
public Organization(int orgId, String orgName, String address, String postalCode, String phoneNo, String email,
String website) {
super();
this.orgId = orgId;
this.orgName = orgName;
this.address = address;
this.postalCode = postalCode;
this.phoneNo = phoneNo;
this.email = email;
this.website = website;
}
// getters and setters
public int getOrgId() {
return orgId;
}
public void setOrgId(int orgId) {
this.orgId = orgId;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
}
| 25.806202 | 125 | 0.704115 |
1e1db3bef3992feec21438a8f36eaa4fcc2ae515 | 157 | package org.dreamwalker.sensorfinder;
/**
* Created by JAICHANGPARK on 10/6/17.
*/
public interface StepListener {
public void step(long timeNs);
}
| 14.272727 | 38 | 0.713376 |
d6965ba516988212f007e5cace64469372fda030 | 1,672 | package com.gallerywithdirectory.library.adapter;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.gallerywithdirectory.library.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import content.Gallery;
public class GridAdapter extends BaseAdapter {
Activity activity;
Gallery gallery;
public GridAdapter(Activity gridActivity, Gallery gallery) {
this.gallery = gallery;
activity = gridActivity;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return gallery.getImages().size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = activity.getLayoutInflater().inflate(R.layout.cell_gallery_grid, null);
holder = new ViewHolder(convertView);
} else
holder = (ViewHolder) convertView.getTag(R.string.Tag_View);
convertView.setTag(R.string.Tag_View, holder);
convertView.setTag(position);
ImageLoader.getInstance().displayImage("file://" + gallery.getImages().get(position).getImagePath(),
holder.imgImage);
return convertView;
}
class ViewHolder{
ImageView imgImage;
public ViewHolder(View convertView) {
imgImage = (ImageView) convertView.findViewById(R.id.imgImage);
}
}
}
| 24.231884 | 102 | 0.758971 |
a09d065c9a178b603f7b26491f6bb9bae490ed8d | 8,426 | package uk.ac.ebi.quickgo.rest.search.query;
import com.google.common.base.Preconditions;
import java.util.*;
/**
* Contains all of the information necessary to put in a search request to a searchable data source.
*/
public class QueryRequest {
private final QuickGOQuery query;
private final Page page;
private final List<Facet> facets;
private final List<QuickGOQuery> filters;
private final List<FieldProjection> projectedFields;
private final List<FieldHighlight> highlightedFields;
private final AggregateRequest aggregate;
private final String highlightStartDelim;
private final String highlightEndDelim;
private final List<SortCriterion> sortCriteria;
private final String collection;
private QueryRequest(Builder builder) {
this.query = builder.query;
this.page = builder.page;
this.facets = Collections.unmodifiableList(new ArrayList<>(builder.facets));
this.filters = new ArrayList<>(builder.filters);
this.projectedFields = new ArrayList<>(builder.projectedFields);
this.highlightedFields = new ArrayList<>(builder.highlightedFields);
this.aggregate = builder.aggregate;
this.highlightStartDelim = builder.highlightStartDelim;
this.highlightEndDelim = builder.highlightEndDelim;
this.sortCriteria = new ArrayList<>(builder.sortCriteria);
this.collection = builder.collection;
}
public QuickGOQuery getQuery() {
return query;
}
public Page getPage() {
return page;
}
public Collection<Facet> getFacets() {
return facets;
}
public List<QuickGOQuery> getFilters() {
return Collections.unmodifiableList(filters);
}
public void addFilter(QuickGOQuery filterQuery) {
filters.add(filterQuery);
}
public List<FieldHighlight> getHighlightedFields() {
return highlightedFields;
}
public List<FieldProjection> getProjectedFields() {
return projectedFields;
}
public AggregateRequest getAggregate() {
return aggregate;
}
public String getHighlightStartDelim() {
return highlightStartDelim;
}
public String getHighlightEndDelim() {
return highlightEndDelim;
}
public List<SortCriterion> getSortCriteria() {
return sortCriteria;
}
public String getCollection() {
return collection;
}
public static class Builder {
private QuickGOQuery query;
private Page page;
private Set<Facet> facets;
private Set<QuickGOQuery> filters;
private Set<FieldProjection> projectedFields;
private Set<FieldHighlight> highlightedFields;
private AggregateRequest aggregate;
private String highlightStartDelim;
private String highlightEndDelim;
private Set<SortCriterion> sortCriteria;
private String collection;
public Builder(QuickGOQuery query, String collection) {
Preconditions.checkArgument(query != null, "Query cannot be null");
Preconditions.checkArgument(collection != null && !collection.isEmpty(), "Collection cannot be null");
this.query = query;
this.collection = collection;
facets = new LinkedHashSet<>();
filters = new LinkedHashSet<>();
sortCriteria = new LinkedHashSet<>();
projectedFields = new LinkedHashSet<>();
highlightedFields = new LinkedHashSet<>();
}
public Builder setPage(Page page) {
this.page = page;
return this;
}
public Builder addSortCriterion(String sortField, SortCriterion.SortOrder sortOrder) {
this.sortCriteria.add(new SortCriterion(sortField, sortOrder));
return this;
}
public Builder addFacetField(String facet) {
facets.add(new Facet(facet));
return this;
}
public Builder addQueryFilter(QuickGOQuery filter) {
this.filters.add(filter);
return this;
}
public Builder addHighlightedField(String field) {
this.highlightedFields.add(new FieldHighlight(field));
return this;
}
public Builder addProjectedField(String field) {
this.projectedFields.add(new FieldProjection(field));
return this;
}
public Builder setAggregate(AggregateRequest aggregate) {
this.aggregate = aggregate;
return this;
}
public Builder setHighlightStartDelim(String highlightStartDelim) {
this.highlightStartDelim = highlightStartDelim;
return this;
}
public Builder setHighlightEndDelim(String highlightEndDelim) {
this.highlightEndDelim = highlightEndDelim;
return this;
}
public QueryRequest build() {
return new QueryRequest(this);
}
}
@Override public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QueryRequest that = (QueryRequest) o;
if (query != null ? !query.equals(that.query) : that.query != null) {
return false;
}
if (page != null ? !page.equals(that.page) : that.page != null) {
return false;
}
if (facets != null ? !facets.equals(that.facets) : that.facets != null) {
return false;
}
if (filters != null ? !filters.equals(that.filters) : that.filters != null) {
return false;
}
if (projectedFields != null ? !projectedFields.equals(that.projectedFields) : that.projectedFields != null) {
return false;
}
if (highlightedFields != null ? !highlightedFields.equals(that.highlightedFields) :
that.highlightedFields != null) {
return false;
}
if (aggregate != null ? !aggregate.equals(that.aggregate) : that.aggregate != null) {
return false;
}
if (highlightStartDelim != null ? !highlightStartDelim.equals(that.highlightStartDelim) :
that.highlightStartDelim != null) {
return false;
}
if (highlightEndDelim != null ? !highlightEndDelim.equals(that.highlightEndDelim) :
that.highlightEndDelim != null) {
return false;
}
if (collection != null ? !collection.equals(that.collection) : that.collection != null) {
return false;
}
return sortCriteria != null ? sortCriteria.equals(that.sortCriteria) : that.sortCriteria == null;
}
@Override public int hashCode() {
int result = query != null ? query.hashCode() : 0;
result = 31 * result + (page != null ? page.hashCode() : 0);
result = 31 * result + (facets != null ? facets.hashCode() : 0);
result = 31 * result + (filters != null ? filters.hashCode() : 0);
result = 31 * result + (projectedFields != null ? projectedFields.hashCode() : 0);
result = 31 * result + (highlightedFields != null ? highlightedFields.hashCode() : 0);
result = 31 * result + (aggregate != null ? aggregate.hashCode() : 0);
result = 31 * result + (highlightStartDelim != null ? highlightStartDelim.hashCode() : 0);
result = 31 * result + (highlightEndDelim != null ? highlightEndDelim.hashCode() : 0);
result = 31 * result + (sortCriteria != null ? sortCriteria.hashCode() : 0);
result = 31 * result + (collection != null ? collection.hashCode() : 0);
return result;
}
@Override public String toString() {
return "QueryRequest{" +
"query=" + query +
", page=" + page +
", facets=" + facets +
", filters=" + filters +
", projectedFields=" + projectedFields +
", highlightedFields=" + highlightedFields +
", aggregate=" + aggregate +
", highlightStartDelim='" + highlightStartDelim + '\'' +
", highlightEndDelim='" + highlightEndDelim + '\'' +
", sortCriteria=" + sortCriteria +
", collection='" + collection + '\'' +
'}';
}
} | 34.532787 | 117 | 0.604676 |
7988a0d73afd980f5cad0e03b157012a224db2a0 | 123 | /**
*
*/
/**
* 用户组
* @author: 肖学进
* @date: 2018年7月17日 下午5:43:22
*/
package com.jinlong.system.dao.usergroup; | 13.666667 | 41 | 0.552846 |
f13a038bddbaa74887dff92371c1547a55cb36bd | 485 | package io.github.bigbio.pgatk.io.clustering;
import io.github.bigbio.pgatk.io.common.cluster.ClusteringFileSpectrumReference;
import java.util.Comparator;
/**
* Created by jg on 05.01.15.
*/
@Deprecated
public class PeakMzComparator implements Comparator<ClusteringFileSpectrumReference.Peak> {
@Override
public int compare(ClusteringFileSpectrumReference.Peak o1, ClusteringFileSpectrumReference.Peak o2) {
return Double.compare(o1.getMz(), o2.getMz());
}
}
| 28.529412 | 106 | 0.773196 |
e21fcf4f2f418fd6b94423b8f3d8bee1fbbf7c26 | 1,237 | package com.ceiba.reserva.adaptador.dao;
import com.ceiba.infraestructura.jdbc.MapperResult;
import com.ceiba.reserva.modelo.dto.DtoReserva;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
public class MapeoReserva implements RowMapper<DtoReserva>, MapperResult {
@Override
public DtoReserva mapRow(ResultSet resultSet, int rowNum) throws SQLException {
Long id = resultSet.getLong("id");
Long idVehiculo = resultSet.getLong("vehiculo_id");
Long idUsuario = resultSet.getLong("usuario_id");
Double precioTotalReservaCOP = resultSet.getDouble("precio_total_reserva_cop");
Double precioTotalReservaUS = resultSet.getDouble("precio_total_reserva_us");
LocalDateTime fechaInicioReserva = extraerLocalDateTime(resultSet, "fecha_inicio_reserva");
LocalDateTime fechaFinRerserva = extraerLocalDateTime(resultSet, "fecha_fin_rerserva");
LocalDateTime fechaCreacion = extraerLocalDateTime(resultSet, "fecha_creacion");
return new DtoReserva(id, idVehiculo, idUsuario,precioTotalReservaCOP,precioTotalReservaUS, fechaInicioReserva,fechaFinRerserva,fechaCreacion);
}
}
| 44.178571 | 151 | 0.780922 |
bc95e343e32716afaee9ba9fee25a182a6eb821d | 362 | package cn.iocoder.yudao.coreservice.modules.system.service.user;
import cn.iocoder.yudao.coreservice.modules.system.dal.dataobject.user.SysUserDO;
/**
* 后台用户 Service Core 接口
*
* @author 芋道源码
*/
public interface SysUserCoreService {
/**
* 通过用户 ID 查询用户
*
* @param id 用户ID
* @return 用户对象信息
*/
SysUserDO getUser(Long id);
}
| 17.238095 | 81 | 0.665746 |
436ee40f25e4046ef1fd326e746f6d361f754c18 | 511 | package nl.buildforce.sequoia.jpa.processor.core.testmodel;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
//This converter has to be mentioned at all columns it is applicable
@Converter()
public class StringConverter implements AttributeConverter<String, String> {
@Override
public String convertToDatabaseColumn(String entityString) {
return entityString;
}
@Override
public String convertToEntityAttribute(String dbString) {
return dbString;
}
} | 25.55 | 76 | 0.796477 |
f8792cf791dafe0904ad0017458960bfa9b6a739 | 265 | package com.husd.postman.domain.request;
public class PostmanBodyOptionsRaw {
private String language;
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
| 17.666667 | 46 | 0.675472 |
e8c52c681df9936e158b98d96d066362b5427a00 | 1,250 | package au.org.aurin.wif.repo.reports.allocation;
import java.util.List;
import au.org.aurin.wif.model.reports.allocation.AllocationAnalysisReport;
/**
* The Interface AllocationAnalysisReportDao.
*/
public interface AllocationAnalysisReportDao {
/**
* Persist allocation analysis report.
*
* @param allocationAnalysisReport
* the allocation analysis report
* @return the allocation analysis report
*/
AllocationAnalysisReport persistAllocationAnalysisReport(
AllocationAnalysisReport allocationAnalysisReport);
/**
* Find allocation analysis report by id.
*
* @param id
* the id
* @return the allocation analysis report
*/
AllocationAnalysisReport findAllocationAnalysisReportById(String id);
/**
* Delete allocation analysis report.
*
* @param allocationAnalysisReport
* the allocation analysis report
*/
void deleteAllocationAnalysisReport(
AllocationAnalysisReport allocationAnalysisReport);
/**
* Gets the allocation analysis reports.
*
* @param projectId
* the project id
* @return the allocation analysis reports
*/
List<AllocationAnalysisReport> getAllocationAnalysisReports(String projectId);
}
| 25.510204 | 80 | 0.72 |
dac9bf18409aac463db5d04183f658db52e6688c | 407 | package org.geogit.osm.map.internal;
import org.opengis.feature.Feature;
public class MappedFeature {
private Feature feature;
private String path;
public MappedFeature(String path, Feature feature) {
this.path = path;
this.feature = feature;
}
public Feature getFeature() {
return feature;
}
public String getPath() {
return path;
}
} | 16.958333 | 56 | 0.638821 |
b341689bf8152a8c5bc0026721bc5ad38186c5d0 | 758 | package com.gfacloud.did;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class KeyTest {
@Test
public void keyTest() {
String keyID = "keys-1";
String privateKeyHex = "a889f4da49ff8dd6b03d4334723fe3e5ff55ae6a2483de1627bec873b0b73e1e86eabd6abce2f96553251de61def0265784688ff712ce583621a5b181ef21639";
String publicKeyHex = "86eabd6abce2f96553251de61def0265784688ff712ce583621a5b181ef21639";
Key key = new Key(keyID, KeyType.Ed25519, privateKeyHex, publicKeyHex);
assertEquals(keyID, key.getId());
assertEquals(KeyType.Ed25519, key.getType());
assertEquals(privateKeyHex, key.getPrivateKeyHex());
assertEquals(publicKeyHex, key.getPublicKeyHex());
}
}
| 34.454545 | 162 | 0.744063 |
dd32b3188ff1f5656443131d639fb4f23ce80903 | 2,050 | /**
* Copyright © 2015 - 2017 EntDIY JavaEE Development Framework
*
* Site: https://www.entdiy.com, E-Mail: [email protected]
*
* 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.entdiy.sys.dao;
import java.util.List;
import javax.persistence.QueryHint;
import com.entdiy.auth.entity.User;
import com.entdiy.core.dao.jpa.BaseDao;
import com.entdiy.sys.entity.NotifyMessage;
import com.entdiy.sys.entity.NotifyMessageRead;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface NotifyMessageReadDao extends BaseDao<NotifyMessageRead, Long> {
NotifyMessageRead findByNotifyMessageAndReadUser(NotifyMessage notifyMessage, User user);
@Query("from NotifyMessageRead where readUser.id=:readUserId and notifyMessage.id in (:scopeEffectiveMessageIds)")
@QueryHints({ @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
public List<NotifyMessageRead> findByReadUserAndNotifyMessageIn(@Param("readUserId") Long readUserId,
@Param("scopeEffectiveMessageIds") List<Long> scopeEffectiveMessageIds);
@Query("select count(nm) from NotifyMessageRead nm where nm.notifyMessage.id=:notifyMessageId")
@QueryHints({ @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
Integer countByNotifyMessage(@Param("notifyMessageId") Long notifyMessageId);
} | 43.617021 | 118 | 0.779024 |
06389f42f89a4459355d230e670d904b9acdd6da | 1,869 | // ===============================================================================
// Authors: AFRL/RQQD
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of the Air Force. No copyright is claimed in the United States under
// Title 17, U.S. Code. All Other Rights Reserved.
// ===============================================================================
/*
* Created on Aug 12, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.flexdock.docking.props;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
/**
* @author Christopher Butler
*/
public abstract class PropertyChangeListenerFactory {
private static final Vector FACTORIES = new Vector();
public static void addFactory(PropertyChangeListenerFactory factory) {
if(factory!=null)
FACTORIES.add(factory);
}
public static void removeFactory(PropertyChangeListenerFactory factory) {
if(factory!=null)
FACTORIES.remove(factory);
}
public static PropertyChangeListener[] getListeners() {
ArrayList list = new ArrayList(FACTORIES.size());
for(Iterator it=FACTORIES.iterator(); it.hasNext();) {
PropertyChangeListenerFactory factory = (PropertyChangeListenerFactory)it.next();
PropertyChangeListener listener = factory.getListener();
if(listener!=null)
list.add(listener);
}
return (PropertyChangeListener[])list.toArray(new PropertyChangeListener[list.size()]);
}
public abstract PropertyChangeListener getListener();
}
| 35.942308 | 105 | 0.645265 |
73d33ecea0f73f773bce3fd030fe6e25db71ff04 | 1,090 | package goalstrategies;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.StreamSupport;
import gameobject.component.type.ComponentTypes;
/**
* Boss Strategy
* @author Yanbo Fang
*
*/
public class BossStrategy extends AbstractGoalStrategy {
private boolean isBossDead;
public BossStrategy() {
super(DEFAULT_WEIGHT);
}
public BossStrategy(double weight) {
super(weight);
}
@Override
protected void initializeFunction() {
this.setFunction((info, engine, currentWeight) -> {
if (StreamSupport
.stream(Spliterators.spliteratorUnknownSize(info.getWorld().iterator(), Spliterator.ORDERED), false)
.filter(obj -> obj.has(ComponentTypes.BOSS))
.allMatch(boss -> boss.getComponent(ComponentTypes.HEALTH).getCurrentHealth() <= 0.0)) {
isBossDead = true;
currentWeight += this.getWeight();
}
this.notifyObservers(this);
return currentWeight;
});
}
@Override
public String getStatus() {
String status = "Boss Goal: ";
status += (isBossDead) ? "Reached" : "Not Reached";
return status;
}
}
| 20.961538 | 105 | 0.712844 |
ec276a275fe71be6ab1ec9a9029b0a89cbd52e0f | 6,026 | package com.example.a1117p.osam.user;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.File;
import java.util.HashMap;
public class ReciptMgtActivity extends AppCompatActivity {
ListView listView;
ListAdapter adapter;
ImageView profile;
void OvalProfile() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
profile.setBackground(new ShapeDrawable(new OvalShape()));
profile.setClipToOutline(true);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipt_mgt);
showList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ReciptListItem item = (ReciptListItem) adapter.getItem(position);
Intent intent = new Intent(ReciptMgtActivity.this, ReciptEditActivity.class);
intent.putExtra("item", item);
startActivity(intent);
finish();
}
});
profile = findViewById(R.id.profile_img);
if(MySharedPreferences.getProfileImgPath()!=null){
File imgFile = new File(MySharedPreferences.getProfileImgPath());
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
profile.setImageBitmap(myBitmap);
}
}
OvalProfile();
}
void showList() {
final ProgressDialog dialog = new ProgressDialog(ReciptMgtActivity.this);
dialog.setMessage("예약내역을 불러오는 중 입니다.");
dialog.show();
listView = findViewById(R.id.hosts);
new Thread(new Runnable() {
@Override
public void run() {
try {
final String html = RequestHttpURLConnection.request("https://be-light.store/api/user/order", null, true, "GET");
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(html);
adapter = new ListViewAdapter(jsonArray, ReciptMgtActivity.this);
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
listView.setAdapter(adapter);
}
});
} catch (final Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(ReciptMgtActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
finish();
}
});
}
}
}).start();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
final ProgressDialog dialog = new ProgressDialog(ReciptMgtActivity.this);
dialog.setMessage("짐을 찾는 중 입니다.");
dialog.show();
final HashMap<String, String> params = new HashMap<>();
params.put("userId", MySharedPreferences.getId());
params.put("reciptNumber", ListViewAdapter.reciptNo + "");
params.put("randomString", scanResult.getContents());
new Thread(new Runnable() {
@Override
public void run() {
final String html = RequestHttpURLConnection.request("https://be-light.store/api/user/order/status", params, true, "POST");
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
JSONParser parser = new JSONParser();
try {
JSONObject object = (JSONObject) parser.parse(html);
Long status = (Long) object.get("status");
if (status == 200) {
Toast.makeText(ReciptMgtActivity.this, "성공하였습니다.", Toast.LENGTH_LONG).show();
showList();
} else {
Toast.makeText(ReciptMgtActivity.this, "실패하였습니다.", Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
e.printStackTrace();
Toast.makeText(ReciptMgtActivity.this, "에러가 발생하였습니다.", Toast.LENGTH_LONG).show();
}
}
});
}
}).start();
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
| 38.382166 | 143 | 0.55775 |
81b50a6581cb5c0259f15868775c0a0415d786e3 | 2,922 | package solace.io;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import solace.game.WeaponProficiency;
import solace.util.Log;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Hashtable;
/**
* Utility class for loading and referencing weapon proficiencies by name.
* @author Ryan Sandor Richards
*/
public class WeaponProficiencies {
public static final WeaponProficiencies instance = new WeaponProficiencies();
private final Hashtable<String, WeaponProficiency> proficiencies = new Hashtable<>();
/**
* @return The singleton instance of the weapons utility.
*/
public static WeaponProficiencies getInstance() { return instance; }
/**
* Initializes the skills helper by loading all the skills provided in the
* game data directory.
*/
public void reload() throws IOException {
Log.info("Loading weapon proficiencies");
proficiencies.clear();
GameFiles.findWeaponProficiencyFiles().forEach(path -> {
String name = path.getFileName().toString();
try {
String json = new String(Files.readAllBytes(path));
JSONArray all = new JSONArray(json);
for (int i = 0; i < all.length(); i++) {
JSONObject profJson = all.getJSONObject(i);
WeaponProficiency proficiency = new WeaponProficiency(
profJson.getString("name"),
profJson.getString("type"),
profJson.getString("style"),
profJson.getString("skill"),
profJson.getInt("hands"),
Arrays.asList(profJson.getString("damage").split("\\s*,\\s*"))
);
if (has(proficiency.getName())) {
Log.warn(String.format("Duplicate weapon proficiency name '%s' found in '%s', skipping.",
proficiency.getName(), name));
continue;
}
Log.trace(String.format("Adding weapon proficiency '%s'", proficiency.getName()));
proficiencies.put(proficiency.getName(), proficiency);
}
} catch (JSONException je) {
Log.error(String.format("Malformed json in weapon proficiency %s: %s", name, je.getMessage()));
} catch (IOException ioe) {
Log.error(String.format("Unable to load weapon proficiency: %s", name));
ioe.printStackTrace();
}
});
}
/**
* Determines if there is a weapon proficiency with the given name.
* @param name Name of the weapon proficiency.
* @return True if a weapon proficiency with the given name exists, false otherwise.
*/
public boolean has(String name) {
return proficiencies.containsKey(name);
}
/**
* Gets the weapon proficiency with the given name.
* @param name Name of the weapon proficiency.
* @return The weapon proficiency with the given name.
*/
public WeaponProficiency get(String name) {
return proficiencies.get(name);
}
}
| 34.376471 | 103 | 0.662902 |
768884b97f7a2aa757084b2b533387af0b234206 | 6,060 | // This is a library to be used to represent a Graph and various measurments for a Graph
// and to perform optimization using Particle Swarm Optimization (PSO)
// Copyright (C) 2008, 2015 Patrick Olekas
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package psograph.measurements;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.Vector;
import psograph.graph.Edge;
import psograph.graph.Graph;
import psograph.graph.Node;
public class ASPL implements Serializable, IGraphMeasument
{
/**
*
*/
private static final long serialVersionUID = -3199607653710066896L;
public ASPL(Graph g)
{
m_graph = g;
m_isCalculated = false;
m_solns = new Graph[m_graph.getNumberOfNodes()];
}
double determineSPL(boolean inverse) throws Exception
{
double value = 0;
Vector<Integer> vhn = new Vector<Integer>(m_graph.getHeaderNodesMap().keySet());
double number_of_edges = m_graph.getNumberOfNodes() * (m_graph.getNumberOfNodes() - 1);
for(int i =0; i < vhn.size(); i++)
{
initSolutionGraph();
Graph totallyTemp = new Graph(m_graph);
evaulateNodeWithBFS(vhn.get(i), totallyTemp);
double val;
if(inverse)
{
val = calcValues.sumInverseWeights()/2.0;
//System.out.println("Sum all weights " + val);
}
else
{
val = calcValues.SumAllWeights()/2.0;
}
val = val/number_of_edges;
if(inverse)
{
//System.out.println("perform calc " + val);
}
value += val;
//TODO: turn this back on
m_solns[i] = new Graph(calcValues);
totallyTemp = null;
}
m_isCalculated = true;
return value;
}
void initSolutionGraph() throws Exception
{
calcValues = new Graph(0);
//First add in nodes
Vector<Integer> vhn = new Vector<Integer>(m_graph.getHeaderNodesMap().keySet());
for(int i =0; i < vhn.size(); i++)
{
calcValues.addNode(vhn.get(i), m_graph.getHeaderNodesMap().get(vhn.get(i)).getX(),
m_graph.getHeaderNodesMap().get(vhn.get(i)).getY() );
}
}
public double Measure() throws Exception
{
double value = -1;
if(m_graph.isFullyConnected() == false)
{
//System.out.println("ASPL - This measure is not accurate for a network with any disconnected nodes");
return value;
}
value = determineSPL(false);
//calcValues.printWithWeights();
//value = peformCalculation();
return value;
}
void evaulateNodeWithBFS(int NodeId , Graph g) throws Exception
{
//initialize the visit map
m_visited = new TreeMap<Integer,Boolean>();
LinkedList<Integer> m_linkedList = new LinkedList<Integer>();
Node n =g.getHeaderNodesMap().get(NodeId);
m_visited.put(n.getID(), true);
n.setDepth(0);
m_linkedList.add(n.getID());
while (!m_linkedList.isEmpty())
{
int u = m_linkedList.remove();
//visit node
Node node = g.getHeaderNodesMap().get(u);
TreeMap<Integer,Edge> tci = node.getNeighbors();
if(tci == null)
{
continue;
}
int i =0;
Vector<Integer> vci = new Vector<Integer>(tci.keySet());
for(i=0; i < vci.size(); i++)
{
if (!IfValidUnvisitedNode(vci.get(i)))
continue;
g.getHeaderNodesMap().get(vci.get(i)).setDepth(node.getDepth() +1);
m_linkedList.add(vci.get(i));
m_visited.put(vci.get(i), true);
//System.out.println("u " + u + " | next_node "
// + vci.get(i));
}
}
//Now that we have a graph with depth, we can make connections for this node.
Vector<Integer> vhn = new Vector<Integer>(g.getHeaderNodesMap().keySet());
for(int i =0; i < vhn.size(); i++)
{
if(g.getHeaderNodesMap().get(vhn.get(i)).getID() == NodeId)
continue;
if(calcValues.getHeaderNodesMap().get(NodeId).isConnectedTo(g.getHeaderNodesMap().get(vhn.get(i))) == false)
{
calcValues.addConnection(NodeId, g.getHeaderNodesMap().get(vhn.get(i)).getID(), g.getHeaderNodesMap().get(vhn.get(i)).getDepth());
}
}
}
boolean IfValidUnvisitedNode(int id) throws Exception
{
if( m_visited.get(id) == null )
return true;
else
return false;
}
public boolean isCalculated()
{
return m_isCalculated;
}
public TreeMap<Integer, Integer> getSPLDistribution() throws Exception
{
if(m_graph.isFullyConnected() == false)
{
//System.out.println("ASPL - This measure is not accurate for a network with any disconnected nodes");
return null;
}
TreeMap<Integer, Integer> result = new TreeMap<Integer, Integer>();
for(int i = 0; i < m_graph.getNumberOfNodes(); i++)
{
TreeMap<Double, Integer> iteration = m_solns[i].getWeightDistribution();
Vector<Double> vWeight = new Vector<Double>(iteration.keySet());
for(int j =0; j < vWeight.size(); j++)
{
double val =vWeight.get(j);
int count = iteration.get(val);
if(result.containsKey((int)Math.rint(val)))
{
count += result.get((int)Math.rint(val));
}
int intVal = (int)Math.rint(val);
result.put(intVal, count);
}
}
return result;
}
public Graph calcValues;
TreeMap<Integer,Boolean> m_visited;
Graph m_graph; // the original graph
Graph m_solns[];
boolean m_isCalculated;
}
| 25.787234 | 135 | 0.634323 |
a7cf2325fe4546d2df389864b7f4e2f6b9874eb3 | 802 | package software.amazon.jsii.tests.calculator.lib;
/**
* The general contract for a concrete number.
*/
@javax.annotation.Generated(value = "jsii-pacmak")
public interface IDoublable extends software.amazon.jsii.JsiiSerializable {
java.lang.Number getDoubleValue();
/**
* A proxy class which represents a concrete javascript instance of this type.
*/
final static class Jsii$Proxy extends software.amazon.jsii.JsiiObject implements software.amazon.jsii.tests.calculator.lib.IDoublable {
protected Jsii$Proxy(final software.amazon.jsii.JsiiObject.InitializationMode mode) {
super(mode);
}
@Override
public java.lang.Number getDoubleValue() {
return this.jsiiGet("doubleValue", java.lang.Number.class);
}
}
}
| 33.416667 | 139 | 0.700748 |
1aa8ff6b8f2ef2bc103c34f72bb93b088acfaa31 | 24,007 | package q.rorbin.verticaltablayout;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import java.util.ArrayList;
import java.util.List;
import q.rorbin.verticaltablayout.widget.QTabView;
import q.rorbin.verticaltablayout.widget.TabIndicator;
import q.rorbin.verticaltablayout.widget.TabView;
/**
* @author chqiu
* Email:[email protected]
*/
public class VerticalTabLayout extends ScrollView {
private Context mContext;
private TabStrip mTabStrip;
private int mColorIndicator;
private TabView mSelectedTab;
private int mTabMargin;
private int mIndicatorWidth;
private int mIndicatorGravity;
private float mIndicatorCorners;
private TabIndicator mIndicator;
private int mTabMode;
private int mTabHeight;
private boolean mStickSlide;
public static int TAB_MODE_FIXED = 10;
public static int TAB_MODE_SCROLLABLE = 11;
private ViewPager mViewPager;
private PagerAdapter mPagerAdapter;
private TabAdapter mTabAdapter;
private List<OnTabSelectedListener> mTabSelectedListeners;
private OnTabPageChangeListener mTabPageChangeListener;
private DataSetObserver mPagerAdapterObserver;
public VerticalTabLayout(Context context) {
this(context, null);
}
public VerticalTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public VerticalTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
setFillViewport(true);
mTabSelectedListeners = new ArrayList<>();
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.VerticalTabLayout);
mColorIndicator = typedArray.getColor(R.styleable.VerticalTabLayout_indicator_color,
context.getResources().getColor(R.color.colorAccent));
mIndicatorWidth = (int) typedArray.getDimension(R.styleable.VerticalTabLayout_indicator_width, dp2px(3));
mIndicatorCorners = typedArray.getDimension(R.styleable.VerticalTabLayout_indicator_corners, 0);
mIndicatorGravity = typedArray.getInteger(R.styleable.VerticalTabLayout_indicator_gravity, Gravity.LEFT);
mTabMargin = (int) typedArray.getDimension(R.styleable.VerticalTabLayout_tab_margin, 0);
mTabMode = typedArray.getInteger(R.styleable.VerticalTabLayout_tab_mode, TAB_MODE_FIXED);
mStickSlide = typedArray.getBoolean(R.styleable.VerticalTabLayout_tab_slide_stick, false);
mTabHeight = (int) typedArray.getDimension(R.styleable.VerticalTabLayout_tab_height, -2);
typedArray.recycle();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (getChildCount() > 0) removeAllViews();
initTabStrip();
}
private void initTabStrip() {
mTabStrip = new TabStrip(mContext);
addView(mTabStrip, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
public void removeAllTabs() {
mTabStrip.removeAllViews();
mSelectedTab = null;
}
public TabView getTabAt(int position) {
return (TabView) mTabStrip.getChildAt(position);
}
private void addTabWithMode(TabView tabView) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
initTabWithMode(params);
mTabStrip.addView(tabView, params);
if (mTabStrip.indexOfChild(tabView) == 0) {
tabView.setChecked(true);
params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
params.setMargins(0, 0, 0, 0);
tabView.setLayoutParams(params);
mSelectedTab = tabView;
}
}
private void initTabWithMode(LinearLayout.LayoutParams params) {
if (mTabMode == TAB_MODE_FIXED) {
params.height = 0;
params.weight = 1.0f;
params.setMargins(0, 0, 0, 0);
} else if (mTabMode == TAB_MODE_SCROLLABLE) {
params.height = mTabHeight;
params.weight = 0f;
params.setMargins(0, mTabMargin, 0, 0);
}
}
private void scrollToTab(int position) {
final TabView tabView = getTabAt(position);
tabView.post(new Runnable() {
@Override
public void run() {
int y = getScrollY();
int tabTop = tabView.getTop() + tabView.getHeight() / 2 - y;
int target = getHeight() / 2;
if (tabTop > target) {
smoothScrollBy(0, tabTop - target);
} else if (tabTop < target) {
smoothScrollBy(0, tabTop - target);
}
}
});
}
private float mLastPositionOffset;
private void scrollByTab(int position, final float positionOffset) {
final TabView tabView = getTabAt(position);
int y = getScrollY();
int tabTop = tabView.getTop() + tabView.getHeight() / 2 - y;
int target = getHeight() / 2;
int nextScrollY = tabView.getHeight() + mTabMargin;
if (positionOffset > 0) {
float percent = positionOffset - mLastPositionOffset;
if (tabTop > target) {
smoothScrollBy(0, (int) (nextScrollY * percent));
}
}
mLastPositionOffset = positionOffset;
}
public void addTab(TabView tabView) {
if (tabView != null) {
addTabWithMode(tabView);
tabView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
int position = mTabStrip.indexOfChild(view);
setTabSelected(position);
}
});
} else {
throw new IllegalStateException("tabview can't be null");
}
}
public void setTabSelected(int position) {
TabView view = getTabAt(position);
for (int i = 0; i < mTabSelectedListeners.size(); i++) {
OnTabSelectedListener listener = mTabSelectedListeners.get(i);
if (listener != null) {
if (view == mSelectedTab) {
listener.onTabReselected(view, position);
} else {
listener.onTabSelected(view, position);
}
}
}
if (view != mSelectedTab) {
mSelectedTab.setChecked(false);
view.setChecked(true);
// if (mViewPager == null)
mTabStrip.moveIndicator(position);
mSelectedTab = view;
scrollToTab(position);
}
}
public void setTabBadge(int tabPosition, int badgeNum) {
getTabAt(tabPosition).setBadge(badgeNum);
}
public void setTabMode(int mode) {
if (mode != TAB_MODE_FIXED && mode != TAB_MODE_SCROLLABLE) {
throw new IllegalStateException("only support TAB_MODE_FIXED or TAB_MODE_SCROLLABLE");
}
if (mode == mTabMode) return;
mTabMode = mode;
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
View view = mTabStrip.getChildAt(i);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
initTabWithMode(params);
if (i == 0) {
params.setMargins(0, 0, 0, 0);
}
view.setLayoutParams(params);
}
mTabStrip.invalidate();
mTabStrip.post(new Runnable() {
@Override
public void run() {
mTabStrip.updataIndicatorMargin();
}
});
}
/**
* only in TAB_MODE_SCROLLABLE mode will be supported
*
* @param margin margin
*/
public void setTabMargin(int margin) {
if (margin == mTabMargin) return;
mTabMargin = margin;
if (mTabMode == TAB_MODE_FIXED) return;
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
View view = mTabStrip.getChildAt(i);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.setMargins(0, i == 0 ? 0 : mTabMargin, 0, 0);
view.setLayoutParams(params);
}
mTabStrip.invalidate();
mTabStrip.post(new Runnable() {
@Override
public void run() {
mTabStrip.updataIndicatorMargin();
}
});
}
/**
* only in TAB_MODE_SCROLLABLE mode will be supported
*
* @param height height
*/
public void setTabHeight(int height) {
if (height == mTabHeight) return;
mTabHeight = height;
if (mTabMode == TAB_MODE_FIXED) return;
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
View view = mTabStrip.getChildAt(i);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.height = mTabHeight;
view.setLayoutParams(params);
}
mTabStrip.invalidate();
mTabStrip.post(new Runnable() {
@Override
public void run() {
mTabStrip.updataIndicatorMargin();
}
});
}
public void setIndicatorColor(int color) {
mColorIndicator = color;
mTabStrip.invalidate();
}
public void setIndicatorWidth(int width) {
mIndicatorWidth = width;
mTabStrip.setIndicatorGravity();
}
public void setIndicatorCorners(int corners) {
mIndicatorCorners = corners;
mTabStrip.invalidate();
}
/**
* @param gravity only support Gravity.LEFT,Gravity.RIGHT,Gravity.FILL
*/
public void setIndicatorGravity(int gravity) {
if (gravity == Gravity.LEFT || gravity == Gravity.RIGHT || Gravity.FILL == gravity) {
mIndicatorGravity = gravity;
mTabStrip.setIndicatorGravity();
} else {
throw new IllegalStateException("only support Gravity.LEFT,Gravity.RIGHT,Gravity.FILL");
}
}
public void addOnTabSelectedListener(OnTabSelectedListener listener) {
if (listener != null) {
mTabSelectedListeners.add(listener);
}
}
public void setTabAdapter(TabAdapter adapter) {
removeAllTabs();
if (adapter != null) {
mTabAdapter = adapter;
for (int i = 0; i < adapter.getCount(); i++) {
addTab(new QTabView(mContext).setIcon(adapter.getIcon(i))
.setTitle(adapter.getTitle(i)).setBadge(adapter.getBadge(i))
.setBackground(adapter.getBackground(i)));
}
} else {
removeAllTabs();
}
}
public void setupWithViewPager(@Nullable ViewPager viewPager) {
if (mViewPager != null && mTabPageChangeListener != null) {
mViewPager.removeOnPageChangeListener(mTabPageChangeListener);
}
if (viewPager != null) {
final PagerAdapter adapter = viewPager.getAdapter();
if (adapter == null) {
throw new IllegalArgumentException("ViewPager does not have a PagerAdapter set");
}
mViewPager = viewPager;
if (mTabPageChangeListener == null) {
mTabPageChangeListener = new OnTabPageChangeListener();
}
viewPager.addOnPageChangeListener(mTabPageChangeListener);
addOnTabSelectedListener(new OnTabSelectedListener() {
@Override
public void onTabSelected(TabView tab, int position) {
if (mViewPager != null && mViewPager.getAdapter().getCount() >= position) {
mViewPager.setCurrentItem(position);
}
}
@Override
public void onTabReselected(TabView tab, int position) {
}
});
setPagerAdapter(adapter, true);
} else {
mViewPager = null;
setPagerAdapter(null, true);
}
}
private void setPagerAdapter(@Nullable final PagerAdapter adapter, final boolean addObserver) {
if (mPagerAdapter != null && mPagerAdapterObserver != null) {
mPagerAdapter.unregisterDataSetObserver(mPagerAdapterObserver);
}
mPagerAdapter = adapter;
if (addObserver && adapter != null) {
if (mPagerAdapterObserver == null) {
mPagerAdapterObserver = new PagerAdapterObserver();
}
adapter.registerDataSetObserver(mPagerAdapterObserver);
}
populateFromPagerAdapter();
}
private void populateFromPagerAdapter() {
removeAllTabs();
if (mPagerAdapter != null) {
final int adapterCount = mPagerAdapter.getCount();
for (int i = 0; i < adapterCount; i++) {
if (mPagerAdapter instanceof TabAdapter) {
mTabAdapter = (TabAdapter) mPagerAdapter;
addTab(new QTabView(mContext).setIcon(mTabAdapter.getIcon(i))
.setTitle(mTabAdapter.getTitle(i)).setBadge(mTabAdapter.getBadge(i))
.setBackground(mTabAdapter.getBackground(i)));
} else {
String title = mPagerAdapter.getPageTitle(i) == null ? "tab" + i : mPagerAdapter.getPageTitle(i).toString();
addTab(new QTabView(mContext).setTitle(
new QTabView.TabTitle.Builder(mContext).setContent(title).build()));
}
}
// Make sure we reflect the currently set ViewPager item
if (mViewPager != null && adapterCount > 0) {
final int curItem = mViewPager.getCurrentItem();
if (curItem != getSelectedTabPosition() && curItem < getTabCount()) {
setTabSelected(curItem);
}
}
} else {
removeAllTabs();
}
}
private int getTabCount() {
return mTabStrip.getChildCount();
}
private int getSelectedTabPosition() {
// if (mViewPager != null) return mViewPager.getCurrentItem();
int index = mTabStrip.indexOfChild(mSelectedTab);
return index == -1 ? 0 : index;
}
private class TabStrip extends LinearLayout {
private float mIndicatorY;
private float mIndicatorX;
private float mIndicatorBottomY;
private int mLastWidth;
private int mIndicatorHeight;
private Paint mIndicatorPaint;
//record invalidate count,used to initialize on mIndicatorBottomY
private long mInvalidateCount;
public TabStrip(Context context) {
super(context);
setWillNotDraw(false);
setOrientation(LinearLayout.VERTICAL);
mIndicatorPaint = new Paint();
mIndicatorGravity = mIndicatorGravity == 0 ? Gravity.LEFT : mIndicatorGravity;
setIndicatorGravity();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mIndicatorBottomY = mIndicatorHeight;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (getChildCount() > 0) {
View childView = getChildAt(0);
mIndicatorHeight = childView.getMeasuredHeight();
if (mInvalidateCount == 0) {
mIndicatorBottomY = mIndicatorHeight;
}
mInvalidateCount++;
}
}
protected void updataIndicatorMargin() {
int index = getSelectedTabPosition();
mIndicatorY = calcIndicatorY(index);
mIndicatorBottomY = mIndicatorY + mIndicatorHeight;
invalidate();
}
protected void setIndicatorGravity() {
if (mIndicatorGravity == Gravity.LEFT) {
mIndicatorX = 0;
if (mLastWidth != 0) mIndicatorWidth = mLastWidth;
setPadding(mIndicatorWidth, 0, 0, 0);
} else if (mIndicatorGravity == Gravity.RIGHT) {
if (mLastWidth != 0) mIndicatorWidth = mLastWidth;
setPadding(0, 0, mIndicatorWidth, 0);
} else if (mIndicatorGravity == Gravity.FILL) {
mIndicatorX = 0;
setPadding(0, 0, 0, 0);
}
post(new Runnable() {
@Override
public void run() {
if (mIndicatorGravity == Gravity.RIGHT) {
mIndicatorX = getWidth() - mIndicatorWidth;
} else if (mIndicatorGravity == Gravity.FILL) {
mLastWidth = mIndicatorWidth;
mIndicatorWidth = getWidth();
}
invalidate();
}
});
}
private float calcIndicatorY(float offset) {
if (mTabMode == TAB_MODE_FIXED)
return offset * mIndicatorHeight;
return offset * (mIndicatorHeight + mTabMargin);
}
protected void moveIndicator(float offset) {
mIndicatorY = calcIndicatorY(offset);
mIndicatorBottomY = mIndicatorY + mIndicatorHeight;
invalidate();
}
/**
* move indicator to a tab location
*
* @param index tab location's index
*/
protected void moveIndicator(final int index) {
final int direction = index - getSelectedTabPosition();
final float target = calcIndicatorY(index);
final float targetBottom = target + mIndicatorHeight;
if (mIndicatorY == target) return;
post(new Runnable() {
@Override
public void run() {
ValueAnimator anime = null;
if (direction > 0) {
anime = ValueAnimator.ofFloat(mIndicatorBottomY, targetBottom);
anime.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = Float.parseFloat(animation.getAnimatedValue().toString());
mIndicatorBottomY = value;
invalidate();
}
});
if (mStickSlide) {
anime.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
slideDown(target);
}
});
} else {
slideDown(target);
}
} else if (direction < 0) {
anime = ValueAnimator.ofFloat(mIndicatorY, target);
anime.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = Float.parseFloat(animation.getAnimatedValue().toString());
mIndicatorY = value;
invalidate();
}
});
if (mStickSlide) {
anime.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
slideUp(targetBottom);
}
});
} else {
slideUp(targetBottom);
}
}
if (anime != null) {
anime.setDuration(100).start();
}
}
});
}
private void slideUp(float targetBottom) {
ValueAnimator anime2 = ValueAnimator.ofFloat(mIndicatorBottomY, targetBottom);
anime2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = Float.parseFloat(animation.getAnimatedValue().toString());
mIndicatorBottomY = value;
invalidate();
}
});
anime2.setDuration(100).start();
}
private void slideDown(float target) {
ValueAnimator anime2 = ValueAnimator.ofFloat(mIndicatorY, target);
anime2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = Float.parseFloat(animation.getAnimatedValue().toString());
mIndicatorY = value;
invalidate();
}
});
anime2.setDuration(100).start();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mIndicatorPaint.setColor(mColorIndicator);
RectF r = new RectF(mIndicatorX, mIndicatorY,
mIndicatorX + mIndicatorWidth, mIndicatorBottomY);
if (mIndicatorCorners != 0) {
canvas.drawRoundRect(r, mIndicatorCorners, mIndicatorCorners, mIndicatorPaint);
} else {
canvas.drawRect(r, mIndicatorPaint);
}
}
}
protected int dp2px(float dp) {
final float scale = mContext.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
private class OnTabPageChangeListener implements ViewPager.OnPageChangeListener {
public OnTabPageChangeListener() {
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
// mTabStrip.moveIndicator(positionOffset + position);
}
@Override
public void onPageSelected(int position) {
if (position != getSelectedTabPosition() && !getTabAt(position).isPressed()) {
setTabSelected(position);
}
}
}
private class PagerAdapterObserver extends DataSetObserver {
@Override
public void onChanged() {
populateFromPagerAdapter();
}
@Override
public void onInvalidated() {
populateFromPagerAdapter();
}
}
public interface OnTabSelectedListener {
void onTabSelected(TabView tab, int position);
void onTabReselected(TabView tab, int position);
}
}
| 36.596037 | 128 | 0.569167 |
96f42656dd1a3f0e446b74de0a8f4b6d21eb351a | 650 | package com.powerapi.dao;
import com.powerapi.utils.CommonUtils;
import java.io.IOException;
public class GitDao {
private static final GitDao INSTANCE = new GitDao();
private GitDao(){
}
public static GitDao getInstance(){
return INSTANCE;
}
public String getCommitName(){
String[] cmd = {"sh", "-c", "git describe --always"};
String back = "";
try {
Process powerapiProc = Runtime.getRuntime().exec(cmd);
back += CommonUtils.readProcessus(powerapiProc);
} catch (IOException e) {
e.printStackTrace();
}
return back;
}
}
| 21.666667 | 66 | 0.590769 |
ec3dd2a912d892edead2a7a80f484c423c7fa21d | 357 | package com.codingame.game.action;
import com.codingame.game.gameEntities.Robot;
public class Attack extends Action{
public Attack(Robot executor, Robot target){
super(executor,1);
this.target = target;
}
private final Robot target;
@Override
public void performAction(){
getExecutor().ATTACK(target);
}
}
| 21 | 48 | 0.67507 |
015b6acfd285b4af95dbf66e32f2bc717f2c55fc | 13,039 | package com.genexus.cryptography.asymmetric;
import java.io.UnsupportedEncodingException;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.BufferedAsymmetricBlockCipher;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.encodings.ISO9796d1Encoding;
import org.bouncycastle.crypto.encodings.OAEPEncoding;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.util.encoders.Base64;
import com.genexus.cryptography.asymmetric.utils.AsymmetricEncryptionAlgorithm;
import com.genexus.cryptography.asymmetric.utils.AsymmetricEncryptionPadding;
import com.genexus.cryptography.commons.AsymmetricCipherObject;
import com.genexus.cryptography.hash.Hashing;
import com.genexus.cryptography.hash.utils.HashAlgorithm;
import com.genexus.securityapicommons.commons.Key;
import com.genexus.securityapicommons.config.EncodingUtil;
import com.genexus.securityapicommons.keys.CertificateX509;
import com.genexus.securityapicommons.keys.PrivateKeyManager;
/**
* @author sgrampone
*
*/
public class AsymmetricCipher extends AsymmetricCipherObject {
/**
* AsymmetricCipher class constructor
*/
public AsymmetricCipher() {
super();
}
/******** EXTERNAL OBJECT PUBLIC METHODS - BEGIN ********/
@Override
public String doEncrypt_WithPrivateKey(String hashAlgorithm, String asymmetricEncryptionPadding, PrivateKeyManager key, String plainText) {
if (this.hasError()) {
return "";
}
return doEncryptInternal(hashAlgorithm, asymmetricEncryptionPadding, key, true, plainText);
}
@Override
public String doEncrypt_WithPublicKey(String hashAlgorithm, String asymmetricEncryptionPadding, CertificateX509 certificate, String plainText) {
if (this.hasError()) {
return "";
}
return doEncryptInternal(hashAlgorithm, asymmetricEncryptionPadding, certificate, false, plainText);
}
@Override
public String doDecrypt_WithPrivateKey(String hashAlgorithm, String asymmetricEncryptionPadding, PrivateKeyManager key, String encryptedInput) {
if (this.hasError()) {
return "";
}
return doDecryptInternal(hashAlgorithm, asymmetricEncryptionPadding, key, true, encryptedInput);
}
@Override
public String doDecrypt_WithPublicKey(String hashAlgorithm, String asymmetricEncryptionPadding, CertificateX509 certificate, String encryptedInput) {
if (this.hasError()) {
return "";
}
return doDecryptInternal(hashAlgorithm, asymmetricEncryptionPadding, certificate, false, encryptedInput);
}
/******** EXTERNAL OBJECT PUBLIC METHODS - END ********/
/**
* @param asymmetricEncryptionAlgorithm
* String AsymmetricEncryptionAlgorithm enum, algorithm name
* @param hashAlgorithm
* String HashAlgorithm enum, algorithm name
* @param asymmetricEncryptionPadding
* String AsymmetricEncryptionPadding enum, padding name
* @param keyPath
* String path to key/certificate
* @param isPrivate
* boolean true if key is provate, false if it is public
* @param alias
* String keystore/certificate pkcs12 format alias
* @param password
* Srting keysore/certificate pkcs12 format alias
* @param plainText
* String UTF-8 to encrypt
* @return String Base64 encrypted plainText text
*/
private String doEncryptInternal(String hashAlgorithm, String asymmetricEncryptionPadding, Key key, boolean isPrivate,
String plainText) {
error.cleanError();
HashAlgorithm hash = HashAlgorithm.getHashAlgorithm(hashAlgorithm, this.error);
AsymmetricEncryptionPadding padding = AsymmetricEncryptionPadding
.getAsymmetricEncryptionPadding(asymmetricEncryptionPadding, this.error);
if (this.error.existsError()) {
return "";
}
String asymmetricEncryptionAlgorithm = "";
AsymmetricKeyParameter asymKey = null;
if (isPrivate) {
PrivateKeyManager keyMan = (PrivateKeyManager) key;
if (!keyMan.hasPrivateKey() || keyMan.hasError()) {
this.error = keyMan.getError();
return "";
}
asymmetricEncryptionAlgorithm = keyMan.getPrivateKeyAlgorithm();
asymKey = keyMan.getPrivateKeyParameterForEncryption();
if (keyMan.hasError()) {
this.error = keyMan.getError();
return "";
}
} else {
CertificateX509 cert = (CertificateX509) key;
if (!cert.Inicialized() || cert.hasError()) {
this.error = cert.getError();
return "";
}
asymmetricEncryptionAlgorithm = cert.getPublicKeyAlgorithm();
asymKey = cert.getPublicKeyParameterForEncryption();
if (cert.hasError()) {
this.error = cert.getError();
return "";
}
}
AsymmetricEncryptionAlgorithm algorithm = AsymmetricEncryptionAlgorithm
.getAsymmetricEncryptionAlgorithm(asymmetricEncryptionAlgorithm, this.error);
try {
this.error.cleanError();
return doEncrypt(algorithm, hash, padding, asymKey, plainText);
} catch (InvalidCipherTextException e) {
this.error.setError("AE036", "Algoritmo inválido" + algorithm);
//e.printStackTrace();
return "";
}
}
/**
* @param asymmetricEncryptionAlgorithm
* String AsymmetricEncryptionAlgorithm enum, algorithm name
* @param hashAlgorithm
* String HashAlgorithm enum, algorithm name
* @param asymmetricEncryptionPadding
* String AsymmetricEncryptionPadding enum, padding name
* @param keyPath
* String path to key/certificate
* @param isPrivate
* boolean true if key is provate, false if it is public
* @param alias
* String keystore/certificate pkcs12 format alias
* @param password
* Srting keysore/certificate pkcs12 format alias
* @param encryptedInput
* String Base64 to decrypt
* @return String UTF-8 decypted encryptedInput text
*/
private String doDecryptInternal(String hashAlgorithm, String asymmetricEncryptionPadding, Key key, boolean isPrivate,
String encryptedInput) {
this.error.cleanError();
HashAlgorithm hash = HashAlgorithm.getHashAlgorithm(hashAlgorithm, this.error);
AsymmetricEncryptionPadding padding = AsymmetricEncryptionPadding
.getAsymmetricEncryptionPadding(asymmetricEncryptionPadding, this.error);
if (this.error.existsError()) {
return "";
}
String asymmetricEncryptionAlgorithm = "";
AsymmetricKeyParameter asymKey = null;
if (isPrivate) {
PrivateKeyManager keyMan = (PrivateKeyManager) key;
if (!keyMan.hasPrivateKey() || keyMan.hasError()) {
this.error = keyMan.getError();
return "";
}
asymmetricEncryptionAlgorithm = keyMan.getPrivateKeyAlgorithm();
asymKey = keyMan.getPrivateKeyParameterForEncryption();
if (keyMan.hasError()) {
this.error = keyMan.getError();
return "";
}
} else {
CertificateX509 cert = (CertificateX509) key;
if (!cert.Inicialized() || cert.hasError()) {
this.error = cert.getError();
return "";
}
asymmetricEncryptionAlgorithm = cert.getPublicKeyAlgorithm();
asymKey = cert.getPublicKeyParameterForEncryption();
if (cert.hasError()) {
this.error = cert.getError();
return "";
}
}
AsymmetricEncryptionAlgorithm algorithm = AsymmetricEncryptionAlgorithm
.getAsymmetricEncryptionAlgorithm(asymmetricEncryptionAlgorithm, this.error);
try {
this.error.cleanError();
return doDecyrpt(algorithm, hash, padding, asymKey, encryptedInput);
} catch (InvalidCipherTextException | UnsupportedEncodingException e) {
this.error.setError("AE039", "Algoritmo inválido" + algorithm);
//e.printStackTrace();
return "";
}
}
/**
* @param asymmetricEncryptionAlgorithm
* AsymmetricEncryptionAlgorithm enum, algorithm name
* @param hashAlgorithm
* HashAlgorithm enum, algorithm name
* @param asymmetricEncryptionPadding
* AsymmetricEncryptionPadding enum, padding name
* @param asymmetricKeyParameter
* AsymmetricKeyParameter with loaded key for specified algorithm
* @param encryptedInput
* String Base64 to decrypt
* @return String UTF-8 decypted encryptedInput text
* @throws InvalidCipherTextException
* @throws UnsupportedEncodingException
*/
private String doDecyrpt(AsymmetricEncryptionAlgorithm asymmetricEncryptionAlgorithm, HashAlgorithm hashAlgorithm,
AsymmetricEncryptionPadding asymmetricEncryptionPadding, AsymmetricKeyParameter asymmetricKeyParameter,
String encryptedInput) throws InvalidCipherTextException, UnsupportedEncodingException {
AsymmetricBlockCipher asymEngine = getEngine(asymmetricEncryptionAlgorithm);
Digest hash = getDigest(hashAlgorithm);
AsymmetricBlockCipher cipher = getPadding(asymEngine, hash, asymmetricEncryptionPadding);
BufferedAsymmetricBlockCipher bufferedCipher = new BufferedAsymmetricBlockCipher(cipher);
if (this.error.existsError()) {
return "";
}
bufferedCipher.init(false, asymmetricKeyParameter);
byte[] inputBytes = Base64.decode(encryptedInput);
bufferedCipher.processBytes(inputBytes, 0, inputBytes.length);
byte[] outputBytes = bufferedCipher.doFinal();
if (outputBytes == null || outputBytes.length == 0) {
this.error.setError("AE040", "Asymmetric decryption error");
return "";
}
EncodingUtil eu = new EncodingUtil();
this.error = eu.getError();
return eu.getString(outputBytes);
}
/**
* @param asymmetricEncryptionAlgorithm
* AsymmetricEncryptionAlgorithm enum, algorithm name
* @param hashAlgorithm
* HashAlgorithm enum, algorithm name
* @param asymmetricEncryptionPadding
* AsymmetricEncryptionPadding enum, padding name
* @param asymmetricKeyParameter
* AsymmetricKeyParameter with loaded key for specified algorithm
* @param encryptedInput
* String Base64 to decrypt
* @returnString Base64 encrypted encryptedInput text
* @throws InvalidCipherTextException
*/
private String doEncrypt(AsymmetricEncryptionAlgorithm asymmetricEncryptionAlgorithm, HashAlgorithm hashAlgorithm,
AsymmetricEncryptionPadding asymmetricEncryptionPadding, AsymmetricKeyParameter asymmetricKeyParameter,
String plainText) throws InvalidCipherTextException {
AsymmetricBlockCipher asymEngine = getEngine(asymmetricEncryptionAlgorithm);
Digest hash = getDigest(hashAlgorithm);
AsymmetricBlockCipher cipher = getPadding(asymEngine, hash, asymmetricEncryptionPadding);
BufferedAsymmetricBlockCipher bufferedCipher = new BufferedAsymmetricBlockCipher(cipher);
if (this.error.existsError()) {
return "";
}
bufferedCipher.init(true, asymmetricKeyParameter);
EncodingUtil eu = new EncodingUtil();
byte[] inputBytes = eu.getBytes(plainText);
if (eu.hasError()) {
this.error = eu.getError();
return "";
}
bufferedCipher.processBytes(inputBytes, 0, inputBytes.length);
byte[] outputBytes = bufferedCipher.doFinal();
if (outputBytes == null || outputBytes.length == 0) {
this.error.setError("AE041", "Asymmetric encryption error");
return "";
}
return new String(Base64.encode(outputBytes));
}
/**
* @param asymmetricEncryptionAlgorithm
* AsymmetricEncryptionAlgorithm enum, algorithm name
* @return AsymmetricBlockCipher Engine for the specified algorithm
*/
private AsymmetricBlockCipher getEngine(AsymmetricEncryptionAlgorithm asymmetricEncryptionAlgorithm) {
switch (asymmetricEncryptionAlgorithm) {
case RSA:
return new RSAEngine();
default:
this.error.setError("AE042", "Unrecognized algorithm");
return null;
}
}
/**
* @param hashAlgorithm
* HashAlgorithm enum, algorithm name
* @return Digest Engine for the specified algorithm
*/
private Digest getDigest(HashAlgorithm hashAlgorithm) {
Hashing hash = new Hashing();
Digest digest = hash.createHash(hashAlgorithm);
if (digest == null) {
this.error.setError("AE043", "Unrecognized HashAlgorithm");
return null;
}
return digest;
}
/**
* @param asymBlockCipher
* AsymmetricBlockCipher enum, algorithm name
* @param hash
* Digest Engine for hashing
* @param asymmetricEncryptionPadding
* AsymmetricEncryptionPadding enum, padding name
* @return AsymmetricBlockCipher Engine specific for the algoritm, hash and
* padding
*/
private AsymmetricBlockCipher getPadding(AsymmetricBlockCipher asymBlockCipher, Digest hash,
AsymmetricEncryptionPadding asymmetricEncryptionPadding) {
switch (asymmetricEncryptionPadding) {
case NOPADDING:
return null;
case OAEPPADDING:
if (hash != null) {
return new OAEPEncoding(asymBlockCipher, hash);
} else {
return new OAEPEncoding(asymBlockCipher);
}
case PCKS1PADDING:
return new PKCS1Encoding(asymBlockCipher);
case ISO97961PADDING:
return new ISO9796d1Encoding(asymBlockCipher);
default:
error.setError("AE044", "Unrecognized AsymmetricEncryptionPadding");
return null;
}
}
}
| 35.432065 | 150 | 0.745456 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.