content
stringlengths 15
442k
| obf_code
stringlengths 15
442k
| probability
float64 0
1
| obf_dict
stringlengths 0
13.5k
| lang
stringclasses 3
values | classification
stringclasses 5
values | confiability
stringlengths 1
10
|
---|---|---|---|---|---|---|
package com.ns.common.qrcode;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
/**
* description: 图片操作工具类
* date: 2017-01-18 9:56
*
* @author ArvinZou
* @version 1.0
* @since JDK 1.8
*/
public class ImageKit {
private ImageKit() {
}
/**
* 获取Image对象
*
* @param imageURL 图片URL
* @return BufferedImage
*/
public static BufferedImage getImageURL(String imageURL) throws MalformedURLException {
// BufferedInputStream bis = null;
// HttpURLConnection httpUrl = null;
// URL url = null;
// try {
// url = new URL(imageURL);
// httpUrl = (HttpURLConnection) url.openConnection();
// httpUrl.connect();
// bis = new BufferedInputStream(httpUrl.getInputStream());
//
// return ImageIO.read(bis);
// } catch (IOException ioe) {
// return null;
// } finally {
// try {
// bis.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// httpUrl.disconnect();
// }
Image src = Toolkit.getDefaultToolkit().getImage(new URL(imageURL));
BufferedImage image = toBufferedImage(src);//Image to BufferedImage
return image;
}
/**
* @param imagePath
* @return
*/
public static BufferedImage getImagePath(String imagePath) {
// FileInputStream fis = null;
// try {
// fis = new FileInputStream(imagePath);
// return ImageIO.read(fis);
// } catch (FileNotFoundException e) {
// return null;
// } catch (IOException ioe) {
// return null;
// } finally {
// try {
// fis.close();
// } catch (IOException e) {
// }
// }
Image src = Toolkit.getDefaultToolkit().getImage(imagePath);
BufferedImage image = toBufferedImage(src);//Image to BufferedImage
return image;
}
/**
* 压缩图片
*
* @param src 源图片BufferedImage
* @param maxLength 长或者宽的最大值
*/
public static void compressImage(BufferedImage src, String outImgPath, int maxLength) throws IOException {
// 调整图片大小,并输出图片
resize(src, outImgPath, maxLength);
}
/**
* 压缩图片
*
* @param is 文件输入流
* @param maxLength 长或者宽的最大值
*/
public static void compressImage(InputStream is, String outImgPath, int maxLength) throws IOException {
// 得到图片
BufferedImage src = ImageIO.read(is);
// 调整图片大小,并输出图片
resize(src, outImgPath, maxLength);
}
/**
* 指定长或者宽的最大值来压缩图片
*
* @param srcImgPath :源图片路径
* @param outImgPath :输出的压缩图片的路径
* @param maxLength :长或者宽的最大值
*/
public static void compressImage(String srcImgPath, String outImgPath, int maxLength) {
// 得到图片
BufferedImage src = getBufferedImage(srcImgPath);
// 调整图片大小,并输出图片
resize(src, outImgPath, maxLength);
}
// 调整图片大小,并输出图片
private static void resize(BufferedImage src, String outImgPath, int maxLength) {
if (null != src) {
int old_w = src.getWidth();
// 得到源图宽
int old_h = src.getHeight();
// 得到源图长
int new_w = 0;
// 新图的宽
int new_h = 0;
// 新图的长
// 根据图片尺寸压缩比得到新图的尺寸
if (old_w > old_h) {
// 图片要缩放的比例
new_w = maxLength;
new_h = (int) Math.round(old_h * ((float) maxLength / old_w));
} else {
new_w = (int) Math.round(old_w * ((float) maxLength / old_h));
new_h = maxLength;
}
disposeImage(src, outImgPath, new_w, new_h);
}
}
/**
* 将图片按照指定的图片尺寸压缩
*
* @param srcImgPath 源图片路径
* @param outImgPath 压缩后输出图片路径
* @param new_w 新图片宽度
* @param new_h 新图片高度
*/
public static void compress(String srcImgPath, String outImgPath, int new_w, int new_h) {
BufferedImage src = getBufferedImage(srcImgPath);
disposeImage(src, outImgPath, new_w, new_h);
}
private static BufferedImage getBufferedImage(String srcImgPath) {
BufferedImage srcImage = null;
try {
FileInputStream in = new FileInputStream(srcImgPath);
srcImage = ImageIO.read(in);
} catch (IOException e) {
System.out.println("读取图片文件出错!" + e.getMessage());
}
return srcImage;
}
/**
* 处理图片
*
* @param src 源图片
* @param outImgPath 输出目标图片路径
* @param new_w 新宽度
* @param new_h 新高度
*/
public synchronized static void disposeImage(BufferedImage src, String outImgPath, int new_w, int new_h) {
// 得到图片
int old_w = src.getWidth();
// 得到源图宽
int old_h = src.getHeight();
// 得到源图长
BufferedImage newImg = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
// 判断输入图片的类型
/*
* switch (src.getType()) { case 13: // png,gifnewImg = new
* BufferedImage(new_w, new_h, // BufferedImage.TYPE_4BYTE_ABGR); break;
* default: newImg = new BufferedImage(new_w, new_h,
* BufferedImage.TYPE_INT_RGB); break; }
*/
Graphics2D g = newImg.createGraphics();
// 从原图上取颜色绘制新图
g.drawImage(src, 0, 0, old_w, old_h, null);
g.dispose();
// 根据图片尺寸压缩比得到新图的尺寸
newImg.getGraphics().drawImage(src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0, null);
// 调用方法输出图片文件
outImage(outImgPath, newImg);
}
/**
* 将图片文件输出到指定的路径,并可设定压缩质量
*
* @param outImgPath 文件输出路径
* @param newImg 压缩后图片
*/
private static void outImage(String outImgPath, BufferedImage newImg) {
// 判断输出的文件夹路径是否存在,不存在则创建
File file = new File(outImgPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
} // 输出到文件流
try {
ImageIO.write(newImg, outImgPath.substring(outImgPath.lastIndexOf(".") + 1), new File(outImgPath));
} catch (FileNotFoundException e) {
System.out.println("ERROR:" + e.getMessage());
} catch (IOException e) {
System.out.println("ERROR:" + e.getMessage());
}
}
/**
* 绘制图片
*
* @param baseImage 绘制底图
* @param addImage 附加图片
* @param x 绘画 x 点
* @param y 绘画 y 点
* @param width 绘画宽度
* @param height 绘画高度
* @param outPath 目标文件生成位置 Demo:
* windows - E:\\out.png , linux - home/out.png
* "."只能出现一次,且在后缀名前面
*/
public static void draw(BufferedImage baseImage, BufferedImage addImage, int x, int y, int width, int height, String outPath) {
try {
Graphics g = baseImage.getGraphics();
g.drawImage(addImage, x, y, width, height, null);
OutputStream outImage = new FileOutputStream(outPath);
String format = outPath.substring(outPath.lastIndexOf(".") + 1, outPath.length());
ImageIO.write(baseImage, format, outImage);
} catch (IOException e) {
System.out.println("Exception:" + e.getMessage());
}
}
/**
* 图片裁切
*
* @param x 选择区域左上角的x坐标
* @param y 选择区域左上角的y坐标
* @param width 选择区域的宽度
* @param height 选择区域的高度
* @param srcFis 源图片文件输入流
* @param srcSuffix 源图片文件后缀
* @param descpath 裁切后图片的保存路径
*/
public static void cut(int x, int y, int width, int height,
InputStream srcFis, String srcSuffix, String descpath) {
ImageInputStream iis = null;
try {
Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(srcSuffix);
ImageReader reader = it.next();
iis = ImageIO.createImageInputStream(srcFis);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Rectangle rect = new Rectangle(x, y, width, height);
param.setSourceRegion(rect);
BufferedImage bi = reader.read(0, param);
ImageIO.write(bi, srcSuffix, new File(descpath));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (srcFis != null) {
try {
srcFis.close();
} catch (IOException e) {
e.printStackTrace();
}
srcFis = null;
}
if (iis != null) {
try {
iis.close();
} catch (IOException e) {
e.printStackTrace();
}
iis = null;
}
}
}
/**
* Image convert to BufferedImage
*
* @param image in
* @return BufferedImage
*/
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null),
image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null),
image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
/**
* 绘制文本
*
* @param color
* @param font
* @param x
* @param y
* @param text
* @param baseUrl
* @param tempPath
*/
public static void graphics(Color color, Font font, int x, int y, String text, String baseUrl, String tempPath) {
/*String imageSuffix = baseUrl.substring(baseUrl.lastIndexOf("."));
BufferedImage imageBase = null;
try {
imageBase = ImageKit.getImageURL(baseUrl);
Graphics graphics = imageBase.getGraphics();
graphics.setColor(color);
graphics.setFont(font);
graphics.drawString(text, x, y);
FileUtil.mkDir(tempPath);
OutputStream outImage = new FileOutputStream(tempPath);
ImageIO.write(imageBase, "jpeg", outImage);
//关闭流
// baseIn.close();
outImage.close();
} catch (Exception e) {
e.printStackTrace();
}*/
}
} |
package com.IMPORT_0.common.IMPORT_1;
import IMPORT_2.imageio.ImageIO;
import IMPORT_2.imageio.ImageReadParam;
import IMPORT_2.imageio.IMPORT_3;
import IMPORT_2.imageio.IMPORT_4.ImageInputStream;
import IMPORT_2.IMPORT_5.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.IMPORT_6.Iterator;
/**
* description: 图片操作工具类
* date: 2017-01-18 9:56
*
* @author ArvinZou
* @version 1.0
* @since JDK 1.8
*/
public class ImageKit {
private ImageKit() {
}
/**
* 获取Image对象
*
* @param imageURL 图片URL
* @return BufferedImage
*/
public static BufferedImage getImageURL(String imageURL) throws MalformedURLException {
// BufferedInputStream bis = null;
// HttpURLConnection httpUrl = null;
// URL url = null;
// try {
// url = new URL(imageURL);
// httpUrl = (HttpURLConnection) url.openConnection();
// httpUrl.connect();
// bis = new BufferedInputStream(httpUrl.getInputStream());
//
// return ImageIO.read(bis);
// } catch (IOException ioe) {
// return null;
// } finally {
// try {
// bis.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// httpUrl.disconnect();
// }
Image src = Toolkit.getDefaultToolkit().FUNC_0(new URL(imageURL));
BufferedImage image = toBufferedImage(src);//Image to BufferedImage
return image;
}
/**
* @param imagePath
* @return
*/
public static BufferedImage getImagePath(String imagePath) {
// FileInputStream fis = null;
// try {
// fis = new FileInputStream(imagePath);
// return ImageIO.read(fis);
// } catch (FileNotFoundException e) {
// return null;
// } catch (IOException ioe) {
// return null;
// } finally {
// try {
// fis.close();
// } catch (IOException e) {
// }
// }
Image src = Toolkit.getDefaultToolkit().FUNC_0(imagePath);
BufferedImage image = toBufferedImage(src);//Image to BufferedImage
return image;
}
/**
* 压缩图片
*
* @param src 源图片BufferedImage
* @param maxLength 长或者宽的最大值
*/
public static void FUNC_1(BufferedImage src, String VAR_0, int maxLength) throws CLASS_0 {
// 调整图片大小,并输出图片
resize(src, VAR_0, maxLength);
}
/**
* 压缩图片
*
* @param is 文件输入流
* @param maxLength 长或者宽的最大值
*/
public static void FUNC_1(InputStream is, String VAR_0, int maxLength) throws CLASS_0 {
// 得到图片
BufferedImage src = ImageIO.read(is);
// 调整图片大小,并输出图片
resize(src, VAR_0, maxLength);
}
/**
* 指定长或者宽的最大值来压缩图片
*
* @param srcImgPath :源图片路径
* @param outImgPath :输出的压缩图片的路径
* @param maxLength :长或者宽的最大值
*/
public static void FUNC_1(String srcImgPath, String VAR_0, int maxLength) {
// 得到图片
BufferedImage src = getBufferedImage(srcImgPath);
// 调整图片大小,并输出图片
resize(src, VAR_0, maxLength);
}
// 调整图片大小,并输出图片
private static void resize(BufferedImage src, String VAR_0, int maxLength) {
if (null != src) {
int old_w = src.getWidth();
// 得到源图宽
int old_h = src.getHeight();
// 得到源图长
int new_w = 0;
// 新图的宽
int new_h = 0;
// 新图的长
// 根据图片尺寸压缩比得到新图的尺寸
if (old_w > old_h) {
// 图片要缩放的比例
new_w = maxLength;
new_h = (int) Math.round(old_h * ((float) maxLength / old_w));
} else {
new_w = (int) Math.round(old_w * ((float) maxLength / old_h));
new_h = maxLength;
}
FUNC_2(src, VAR_0, new_w, new_h);
}
}
/**
* 将图片按照指定的图片尺寸压缩
*
* @param srcImgPath 源图片路径
* @param outImgPath 压缩后输出图片路径
* @param new_w 新图片宽度
* @param new_h 新图片高度
*/
public static void compress(String srcImgPath, String VAR_0, int new_w, int new_h) {
BufferedImage src = getBufferedImage(srcImgPath);
FUNC_2(src, VAR_0, new_w, new_h);
}
private static BufferedImage getBufferedImage(String srcImgPath) {
BufferedImage srcImage = null;
try {
FileInputStream in = new FileInputStream(srcImgPath);
srcImage = ImageIO.read(in);
} catch (CLASS_0 VAR_1) {
System.VAR_2.println("读取图片文件出错!" + e.getMessage());
}
return srcImage;
}
/**
* 处理图片
*
* @param src 源图片
* @param outImgPath 输出目标图片路径
* @param new_w 新宽度
* @param new_h 新高度
*/
public synchronized static void FUNC_2(BufferedImage src, String VAR_0, int new_w, int new_h) {
// 得到图片
int old_w = src.getWidth();
// 得到源图宽
int old_h = src.getHeight();
// 得到源图长
BufferedImage newImg = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
// 判断输入图片的类型
/*
* switch (src.getType()) { case 13: // png,gifnewImg = new
* BufferedImage(new_w, new_h, // BufferedImage.TYPE_4BYTE_ABGR); break;
* default: newImg = new BufferedImage(new_w, new_h,
* BufferedImage.TYPE_INT_RGB); break; }
*/
Graphics2D g = newImg.createGraphics();
// 从原图上取颜色绘制新图
g.drawImage(src, 0, 0, old_w, old_h, null);
g.FUNC_3();
// 根据图片尺寸压缩比得到新图的尺寸
newImg.getGraphics().drawImage(src.FUNC_4(new_w, new_h, Image.VAR_3), 0, 0, null);
// 调用方法输出图片文件
FUNC_5(VAR_0, newImg);
}
/**
* 将图片文件输出到指定的路径,并可设定压缩质量
*
* @param outImgPath 文件输出路径
* @param newImg 压缩后图片
*/
private static void FUNC_5(String VAR_0, BufferedImage newImg) {
// 判断输出的文件夹路径是否存在,不存在则创建
File VAR_5 = new File(VAR_0);
if (!VAR_5.getParentFile().exists()) {
VAR_5.getParentFile().FUNC_6();
} // 输出到文件流
try {
ImageIO.write(newImg, VAR_0.substring(VAR_0.lastIndexOf(".") + 1), new File(VAR_0));
} catch (FileNotFoundException VAR_1) {
System.VAR_2.println("ERROR:" + VAR_1.getMessage());
} catch (CLASS_0 VAR_1) {
System.VAR_2.println("ERROR:" + VAR_1.getMessage());
}
}
/**
* 绘制图片
*
* @param baseImage 绘制底图
* @param addImage 附加图片
* @param x 绘画 x 点
* @param y 绘画 y 点
* @param width 绘画宽度
* @param height 绘画高度
* @param outPath 目标文件生成位置 Demo:
* windows - E:\\out.png , linux - home/out.png
* "."只能出现一次,且在后缀名前面
*/
public static void draw(BufferedImage baseImage, BufferedImage VAR_6, int x, int y, int width, int height, String outPath) {
try {
Graphics g = baseImage.getGraphics();
g.drawImage(VAR_6, x, y, width, height, null);
CLASS_1 VAR_4 = new FileOutputStream(outPath);
String VAR_7 = outPath.substring(outPath.lastIndexOf(".") + 1, outPath.FUNC_7());
ImageIO.write(baseImage, VAR_7, VAR_4);
} catch (CLASS_0 VAR_1) {
System.VAR_2.println("Exception:" + VAR_1.getMessage());
}
}
/**
* 图片裁切
*
* @param x 选择区域左上角的x坐标
* @param y 选择区域左上角的y坐标
* @param width 选择区域的宽度
* @param height 选择区域的高度
* @param srcFis 源图片文件输入流
* @param srcSuffix 源图片文件后缀
* @param descpath 裁切后图片的保存路径
*/
public static void FUNC_8(int x, int y, int width, int height,
InputStream srcFis, String srcSuffix, String descpath) {
ImageInputStream iis = null;
try {
Iterator<IMPORT_3> it = ImageIO.getImageReadersByFormatName(srcSuffix);
IMPORT_3 reader = it.next();
iis = ImageIO.FUNC_9(srcFis);
reader.setInput(iis, true);
ImageReadParam param = reader.FUNC_10();
Rectangle rect = new Rectangle(x, y, width, height);
param.FUNC_11(rect);
BufferedImage bi = reader.read(0, param);
ImageIO.write(bi, srcSuffix, new File(descpath));
} catch (CLASS_2 ex) {
ex.FUNC_12();
} finally {
if (srcFis != null) {
try {
srcFis.FUNC_13();
} catch (CLASS_0 VAR_1) {
VAR_1.FUNC_12();
}
srcFis = null;
}
if (iis != null) {
try {
iis.FUNC_13();
} catch (CLASS_0 VAR_1) {
VAR_1.FUNC_12();
}
iis = null;
}
}
}
/**
* Image convert to BufferedImage
*
* @param image in
* @return BufferedImage
*/
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).FUNC_0();
BufferedImage VAR_8 = null;
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
try {
int transparency = VAR_9.OPAQUE;
GraphicsDevice gs = ge.FUNC_14();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
VAR_8 = gc.FUNC_15(image.getWidth(null),
image.getHeight(null), transparency);
} catch (HeadlessException VAR_1) {
// The system does not have a screen
}
if (VAR_8 == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
VAR_8 = new BufferedImage(image.getWidth(null),
image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = VAR_8.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.FUNC_3();
return VAR_8;
}
/**
* 绘制文本
*
* @param color
* @param font
* @param x
* @param y
* @param text
* @param baseUrl
* @param tempPath
*/
public static void graphics(CLASS_3 VAR_10, Font font, int x, int y, String VAR_11, String baseUrl, String tempPath) {
/*String imageSuffix = baseUrl.substring(baseUrl.lastIndexOf("."));
BufferedImage imageBase = null;
try {
imageBase = ImageKit.getImageURL(baseUrl);
Graphics graphics = imageBase.getGraphics();
graphics.setColor(color);
graphics.setFont(font);
graphics.drawString(text, x, y);
FileUtil.mkDir(tempPath);
OutputStream outImage = new FileOutputStream(tempPath);
ImageIO.write(imageBase, "jpeg", outImage);
//关闭流
// baseIn.close();
outImage.close();
} catch (Exception e) {
e.printStackTrace();
}*/
}
} | 0.312838 | {'IMPORT_0': 'ns', 'IMPORT_1': 'qrcode', 'IMPORT_2': 'javax', 'IMPORT_3': 'ImageReader', 'IMPORT_4': 'stream', 'IMPORT_5': 'swing', 'IMPORT_6': 'util', 'FUNC_0': 'getImage', 'FUNC_1': 'compressImage', 'VAR_0': 'outImgPath', 'CLASS_0': 'IOException', 'FUNC_2': 'disposeImage', 'VAR_1': 'e', 'VAR_2': 'out', 'FUNC_3': 'dispose', 'FUNC_4': 'getScaledInstance', 'VAR_3': 'SCALE_SMOOTH', 'FUNC_5': 'outImage', 'VAR_4': 'outImage', 'VAR_5': 'file', 'FUNC_6': 'mkdirs', 'VAR_6': 'addImage', 'CLASS_1': 'OutputStream', 'VAR_7': 'format', 'FUNC_7': 'length', 'FUNC_8': 'cut', 'FUNC_9': 'createImageInputStream', 'FUNC_10': 'getDefaultReadParam', 'FUNC_11': 'setSourceRegion', 'CLASS_2': 'Exception', 'FUNC_12': 'printStackTrace', 'FUNC_13': 'close', 'VAR_8': 'bimage', 'VAR_9': 'Transparency', 'FUNC_14': 'getDefaultScreenDevice', 'FUNC_15': 'createCompatibleImage', 'CLASS_3': 'Color', 'VAR_10': 'color', 'VAR_11': 'text'} | java | OOP | 8.89% |
package p;
public interface A {
public static final int i = 0;
}
| package VAR_0;
public interface CLASS_0 {
public static final int VAR_1 = 0;
}
| 0.552044 | {'VAR_0': 'p', 'CLASS_0': 'A', 'VAR_1': 'i'} | java | Texto | 50.00% |
package com.gmail.imshhui.medium;
import com.gmail.imshhui.bean.TreeNode;
import java.util.HashMap;
import java.util.Map;
/**
* Given a complete binary tree, count the number of nodes.
*
* Note:
*
* Definition of a complete binary tree from Wikipedia:
* In a complete binary tree every level, except possibly the last, is completely filled,
* and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
*
* Example:
*
* Input:
* 1
* / \
* 2 3
* / \ /
* 4 5 6
*
* Output: 6
*
* @see <a href="https://leetcode.com/problems/count-complete-tree-nodes/"></a>
* User: liyulin
* Date: 2019/10/9
*/
public class CountCompleteTreeNodes {
public int countNodes(TreeNode root) {
Map<Integer, Integer> map = new HashMap<>();
levelHelper(root, map, 0);
int nodes = 0;
for (Integer value : map.values()) {
nodes = nodes + value;
}
return nodes;
}
private void levelHelper(TreeNode root, Map<Integer, Integer> map, int high) {
if (root == null) {
return;
}
if (map.containsKey(high)) {
int value = map.get(high);
map.put(high, ++value);
} else {
map.put(high, 1);
}
levelHelper(root.left, map, high + 1);
levelHelper(root.right, map, high + 1);
}
public int countNodes1(TreeNode root) {
if (root == null)
return 0;
return 1 + countNodes1(root.left) + countNodes1(root.right);
}
}
| package IMPORT_0.IMPORT_1.imshhui.IMPORT_2;
import IMPORT_0.IMPORT_1.imshhui.bean.TreeNode;
import java.IMPORT_3.HashMap;
import java.IMPORT_3.Map;
/**
* Given a complete binary tree, count the number of nodes.
*
* Note:
*
* Definition of a complete binary tree from Wikipedia:
* In a complete binary tree every level, except possibly the last, is completely filled,
* and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
*
* Example:
*
* Input:
* 1
* / \
* 2 3
* / \ /
* 4 5 6
*
* Output: 6
*
* @see <a href="https://leetcode.com/problems/count-complete-tree-nodes/"></a>
* User: liyulin
* Date: 2019/10/9
*/
public class CLASS_0 {
public int countNodes(TreeNode root) {
Map<CLASS_1, CLASS_1> map = new HashMap<>();
FUNC_0(root, map, 0);
int VAR_0 = 0;
for (CLASS_1 VAR_1 : map.FUNC_1()) {
VAR_0 = VAR_0 + VAR_1;
}
return VAR_0;
}
private void FUNC_0(TreeNode root, Map<CLASS_1, CLASS_1> map, int high) {
if (root == null) {
return;
}
if (map.containsKey(high)) {
int VAR_1 = map.get(high);
map.FUNC_2(high, ++VAR_1);
} else {
map.FUNC_2(high, 1);
}
FUNC_0(root.VAR_2, map, high + 1);
FUNC_0(root.right, map, high + 1);
}
public int countNodes1(TreeNode root) {
if (root == null)
return 0;
return 1 + countNodes1(root.VAR_2) + countNodes1(root.right);
}
}
| 0.428885 | {'IMPORT_0': 'com', 'IMPORT_1': 'gmail', 'IMPORT_2': 'medium', 'IMPORT_3': 'util', 'CLASS_0': 'CountCompleteTreeNodes', 'CLASS_1': 'Integer', 'FUNC_0': 'levelHelper', 'VAR_0': 'nodes', 'VAR_1': 'value', 'FUNC_1': 'values', 'FUNC_2': 'put', 'VAR_2': 'left'} | java | OOP | 53.74% |
/**
* Adds search history entry.
* @param request user request
*/
public void addEntry(String request, SearchType searchType) {
try {
deleteDuplicates(request, searchType);
historyDao.create(new HistoryEntry(request, searchType));
enforceHistorySizeLimit();
} catch (SQLException e) {
DebugLog.logException(e);
}
} | /**
* Adds search history entry.
* @param request user request
*/
public void addEntry(String request, SearchType VAR_0) {
try {
deleteDuplicates(request, VAR_0);
historyDao.create(new CLASS_0(request, VAR_0));
FUNC_0();
} catch (SQLException e) {
DebugLog.logException(e);
}
} | 0.251165 | {'VAR_0': 'searchType', 'CLASS_0': 'HistoryEntry', 'FUNC_0': 'enforceHistorySizeLimit'} | java | Procedural | 59.62% |
/*
* 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.dungeoncrawler.model;
import com.dungeoncrawler.model.entities.*;
import com.dungeoncrawler.model.items.Amulet;
import com.dungeoncrawler.model.items.DmgAmulet;
import com.dungeoncrawler.model.items.Potion;
import com.dungeoncrawler.model.items.Key;
import java.util.ArrayList;
/**
*
* @author jonathan
*/
public class DungeonGenerator {
public DungeonGenerator(){
}
public Dungeon generateDungeon(int sizeX, int sizeY, int tileSize, Player player){
Dungeon tempDungeon = new Dungeon(player);
int levelAmount = tempDungeon.getLevel().length;
for(int i = 0; i < levelAmount; i++){
tempDungeon.setLevel(generateLevel(sizeX, sizeY, tileSize, i+1), i);
}
return tempDungeon;
}
private Level generateLevel(int sizeX, int sizeY, int tileSize, int lvl){
int roomAmount = (int) (Math.random() * 6) + 5;
Level tempLevel = new Level(roomAmount);
System.out.println(roomAmount);
// TODO: Zufällig Türen setzen
int xPos = roomAmount / 2;
int yPos = roomAmount / 2;
tempLevel.setRoom(generateRoom(sizeX, sizeY, tileSize, lvl, false), xPos, yPos);
// Schleife läuft so lange, bis die entsprechende Anzahl an Räumen generiert wurde
for(int i = 1; i < roomAmount;){
// Zufallszahl für die Richtung wird generiert, Oben: 0, Rechts: 1, Unten: 2, Links: 3
int direction = (int) (Math.random() * 4);
switch (direction) {
// Oben
case 0:
if(yPos != roomAmount - 1){
yPos += 1;
}
break;
// Rechts
case 1:
if(xPos != roomAmount - 1){
xPos += 1;
}
break;
// Unten
case 2:
if(yPos != 0){
yPos -= 1;
}
break;
// Links
case 3:
if(xPos != 0){
xPos -= 1;
}
break;
}
// An der neuen Stelle vom Cursor gibt es noch keinen Raum
if(tempLevel.getRooms()[xPos][yPos] == null){
tempLevel.setRoom(generateRoom(sizeX, sizeY, tileSize, lvl, true), xPos, yPos);
// i darf nur erhöht werden, wenn auch ein Raum generiert wurde
i++;
}
}
int keyRoom = (int) (Math.random()*roomAmount);
int i = 0;
for(int x = 0; x < roomAmount; x++){
for(int y = 0; y < roomAmount; y++){
if(tempLevel.getRooms()[x][y] != null){
if(i == keyRoom){
Item tempItem = new Key(lvl);
ItemContainer tempContainer = new ItemContainer(((sizeX / 2) + 1) * 48, ((sizeY / 2) + 1) * 48, tempItem);
tempLevel.getRooms()[x][y].getItems().add(tempContainer);
}
i++;
}
}
}
// Exit wird generiert
if(lvl >= 7 && false){
tempLevel.setExit(-1, 0);
tempLevel.setExit(-1, 1);
}
else{
boolean istFertig = false;
do{
// Zufallszahl für die Richtung wird generiert, Oben: 0, Rechts: 1, Unten: 2, Links: 3
int direction = (int) (Math.random() * 4);
switch (direction) {
// Oben
case 0:
if(yPos != roomAmount - 1){
yPos += 1;
}
break;
// Rechts
case 1:
if(xPos != roomAmount - 1){
xPos += 1;
}
break;
// Unten
case 2:
if(yPos != 0){
yPos -= 1;
}
break;
// Links
case 3:
if(xPos != 0){
xPos -= 1;
}
break;
}
// An der neuen Stelle vom Cursor gibt es noch keinen Raum
if(tempLevel.getRooms()[xPos][yPos] == null){
tempLevel.setRoom(generateRoom(sizeX, sizeY, tileSize, lvl, false), xPos, yPos);
tempLevel.setExit(xPos, 0);
tempLevel.setExit(yPos, 1);
istFertig = true;
}
} while(!istFertig);
}
return tempLevel;
}
private Room generateRoom(int sizeX, int sizeY, int tileSize, int lvl, boolean allowEnemies){
int itemAmount = (int) (Math.random() * 2);
int enemyAmount = (int) (Math.random() * 5);
Room tempRoom = new Room(new ArrayList<ItemContainer>(itemAmount), new Entity[15]);
if(allowEnemies){
// Items werden generiert
int[][] belegt = new int[itemAmount][2];
for(int j = 0; j < belegt.length; j++){
belegt[j][0] = -1;
belegt[j][1] = -1;
}
for(int i = 0; i < itemAmount; i++){
int xTile;
int yTile;
boolean istFertig = false;
do {
System.out.println("läuft");
// Tiles des Entities werden generiert
xTile = generateTile(sizeX);
yTile = generateTile(sizeY);
// Test, ob Tiles bereits belegt
boolean hatGeklappt = true;
for(int j = 0; j < belegt.length; j++){
if(j != i){
if(xTile == belegt[j][0] && yTile == belegt[j][1]){
hatGeklappt = false;
break;
}
}
}
if(hatGeklappt == true){
// Tiles zum Array hinzufügen
for(int j = 0; j < belegt.length; j++){
if(belegt[j][0] == -1){
belegt[j][0] = xTile;
belegt[j][1] = yTile;
}
}
istFertig = true;
}
} while(!istFertig);
// Berechnung der Positionen
int xPos = xTile * tileSize;
int yPos = yTile * tileSize;
// Typ des Entities wird generiert
Item tempItem;
int id = (int) (Math.random() * 3);
switch(id){
case 0:
tempItem = new Amulet(lvl);
break;
case 1:
tempItem = new Potion(lvl);
break;
case 2:
tempItem = new DmgAmulet(lvl);
break;
default:
tempItem = null;
}
if(tempItem == null){
System.out.println("Es gibt Probleme, schau mal beim Raumgenerator nach. Es sind sogar sehr problematische Probleme mit den Items");
}
if(tempItem != null){
ItemContainer tempContainer;
tempContainer = new ItemContainer(xPos, yPos, tempItem);
tempRoom.getItems().add(tempContainer);
}
}
// Entities werden generiert
belegt = new int[enemyAmount][2];
for(int j = 0; j < belegt.length; j++){
belegt[j][0] = -1;
belegt[j][1] = -1;
}
for(int i = 0; i < enemyAmount; i++){
int xTile;
int yTile;
boolean istFertig = false;
do {
System.out.println("läuft");
// Tiles des Entities werden generiert
xTile = generateTile(sizeX);
yTile = generateTile(sizeY);
// Test, ob Tiles bereits belegt
boolean hatGeklappt = true;
for(int j = 0; j < belegt.length; j++){
if(j != i){
if(xTile == belegt[j][0] && yTile == belegt[j][1]){
hatGeklappt = false;
break;
}
}
}
if(hatGeklappt == true){
// Tiles zum Array hinzufügen
for(int j = 0; j < belegt.length; j++){
if(belegt[j][0] == -1){
belegt[j][0] = xTile;
belegt[j][1] = yTile;
}
}
istFertig = true;
}
} while(!istFertig);
// Berechnung der Positionen
int xPos = xTile * tileSize;
int yPos = yTile * tileSize;
// Typ des Entities wird generiert
Entity temp;
int id = (int) (Math.random() * 16);
switch(id){
case 0:
temp = new Archer(xPos, yPos, lvl);
break;
case 1:
temp = new Swordsman(xPos, yPos, lvl);
break;
case 2:
temp = new Wizard(xPos, yPos, lvl);
break;
case 3:
temp = new Firewizard(xPos, yPos, lvl);
break;
case 4:
temp = new Earthwizard(xPos, yPos, lvl);
break;
case 5:
temp = new Fireswordsman(xPos, yPos, lvl);
break;
case 6:
temp = new Icearcher(xPos, yPos, lvl);
break;
case 7:
temp = new Firearcher(xPos, yPos, lvl);
break;
case 8:
temp = new Iceswordsman(xPos, yPos, lvl);
break;
case 9:
temp = new Icewizard(xPos, yPos, lvl);
break;
case 10:
temp = new Waterwizard(xPos, yPos, lvl);
break;
case 11:
//temp = new Healwizard(xPos, yPos, lvl);
/* wird nicht gespawnt
BUG: HP ueber 100%, also crash in HUD container lol
keine Lust zu beheben
--TODO--
*/
temp = null;
break;
case 12:
temp = new Naturewizard(xPos, yPos, lvl);
break;
case 13:
temp = new Darkwizard(xPos, yPos, lvl);
break;
case 14:
temp = new Darkswordsman(xPos, yPos, lvl);
break;
case 15:
temp = new Darkarcher(xPos, yPos, lvl);
break;
default:
temp = null;
}
if(temp == null){
System.out.println("Es gibt Probleme, schau mal beim Raumgenerator nach. Es sind sogar sehr problematische Probleme");
}
tempRoom.setEnemies(temp, i);
}
}
return tempRoom;
}
private int generateTile(int size){
int tile = ((int) (Math.random() * size) + 1);
return tile;
}
public void ichWillSpielen(Dungeon d){
for(int i=0;i<d.getLevel().length;i++){
Level temp = d.getLevel()[i];
System.out.println("Level " + i);
for(int j = 0; j < temp.getRooms().length; j++){
for(int k = temp.getRooms().length - 1; k >= 0; k--){
if(temp.getRooms()[j][k] == null){
System.out.print("0 ");
}
else{
System.out.print("1 ");
}
}
System.out.println();
}
}
}
}
| /*
* 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 IMPORT_0.dungeoncrawler.IMPORT_1;
import IMPORT_0.dungeoncrawler.IMPORT_1.IMPORT_2.*;
import IMPORT_0.dungeoncrawler.IMPORT_1.IMPORT_3.IMPORT_4;
import IMPORT_0.dungeoncrawler.IMPORT_1.IMPORT_3.IMPORT_5;
import IMPORT_0.dungeoncrawler.IMPORT_1.IMPORT_3.IMPORT_6;
import IMPORT_0.dungeoncrawler.IMPORT_1.IMPORT_3.IMPORT_7;
import IMPORT_8.IMPORT_9.ArrayList;
/**
*
* @author jonathan
*/
public class CLASS_0 {
public CLASS_0(){
}
public CLASS_1 generateDungeon(int VAR_0, int VAR_1, int VAR_2, CLASS_2 player){
CLASS_1 VAR_3 = new CLASS_1(player);
int VAR_4 = VAR_3.FUNC_0().VAR_5;
for(int VAR_6 = 0; VAR_6 < VAR_4; VAR_6++){
VAR_3.setLevel(FUNC_1(VAR_0, VAR_1, VAR_2, VAR_6+1), VAR_6);
}
return VAR_3;
}
private CLASS_3 FUNC_1(int VAR_0, int VAR_1, int VAR_2, int VAR_7){
int VAR_8 = (int) (VAR_9.FUNC_2() * 6) + 5;
CLASS_3 VAR_10 = new CLASS_3(VAR_8);
System.out.FUNC_3(VAR_8);
// TODO: Zufällig Türen setzen
int VAR_11 = VAR_8 / 2;
int VAR_12 = VAR_8 / 2;
VAR_10.setRoom(FUNC_4(VAR_0, VAR_1, VAR_2, VAR_7, false), VAR_11, VAR_12);
// Schleife läuft so lange, bis die entsprechende Anzahl an Räumen generiert wurde
for(int VAR_6 = 1; VAR_6 < VAR_8;){
// Zufallszahl für die Richtung wird generiert, Oben: 0, Rechts: 1, Unten: 2, Links: 3
int VAR_13 = (int) (VAR_9.FUNC_2() * 4);
switch (VAR_13) {
// Oben
case 0:
if(VAR_12 != VAR_8 - 1){
VAR_12 += 1;
}
break;
// Rechts
case 1:
if(VAR_11 != VAR_8 - 1){
VAR_11 += 1;
}
break;
// Unten
case 2:
if(VAR_12 != 0){
VAR_12 -= 1;
}
break;
// Links
case 3:
if(VAR_11 != 0){
VAR_11 -= 1;
}
break;
}
// An der neuen Stelle vom Cursor gibt es noch keinen Raum
if(VAR_10.FUNC_5()[VAR_11][VAR_12] == null){
VAR_10.setRoom(FUNC_4(VAR_0, VAR_1, VAR_2, VAR_7, true), VAR_11, VAR_12);
// i darf nur erhöht werden, wenn auch ein Raum generiert wurde
VAR_6++;
}
}
int VAR_14 = (int) (VAR_9.FUNC_2()*VAR_8);
int VAR_6 = 0;
for(int VAR_15 = 0; VAR_15 < VAR_8; VAR_15++){
for(int VAR_16 = 0; VAR_16 < VAR_8; VAR_16++){
if(VAR_10.FUNC_5()[VAR_15][VAR_16] != null){
if(VAR_6 == VAR_14){
CLASS_4 VAR_17 = new IMPORT_7(VAR_7);
CLASS_5 VAR_18 = new CLASS_5(((VAR_0 / 2) + 1) * 48, ((VAR_1 / 2) + 1) * 48, VAR_17);
VAR_10.FUNC_5()[VAR_15][VAR_16].FUNC_6().add(VAR_18);
}
VAR_6++;
}
}
}
// Exit wird generiert
if(VAR_7 >= 7 && false){
VAR_10.setExit(-1, 0);
VAR_10.setExit(-1, 1);
}
else{
boolean VAR_19 = false;
do{
// Zufallszahl für die Richtung wird generiert, Oben: 0, Rechts: 1, Unten: 2, Links: 3
int VAR_13 = (int) (VAR_9.FUNC_2() * 4);
switch (VAR_13) {
// Oben
case 0:
if(VAR_12 != VAR_8 - 1){
VAR_12 += 1;
}
break;
// Rechts
case 1:
if(VAR_11 != VAR_8 - 1){
VAR_11 += 1;
}
break;
// Unten
case 2:
if(VAR_12 != 0){
VAR_12 -= 1;
}
break;
// Links
case 3:
if(VAR_11 != 0){
VAR_11 -= 1;
}
break;
}
// An der neuen Stelle vom Cursor gibt es noch keinen Raum
if(VAR_10.FUNC_5()[VAR_11][VAR_12] == null){
VAR_10.setRoom(FUNC_4(VAR_0, VAR_1, VAR_2, VAR_7, false), VAR_11, VAR_12);
VAR_10.setExit(VAR_11, 0);
VAR_10.setExit(VAR_12, 1);
VAR_19 = true;
}
} while(!VAR_19);
}
return VAR_10;
}
private CLASS_6 FUNC_4(int VAR_0, int VAR_1, int VAR_2, int VAR_7, boolean VAR_20){
int VAR_21 = (int) (VAR_9.FUNC_2() * 2);
int VAR_22 = (int) (VAR_9.FUNC_2() * 5);
CLASS_6 VAR_23 = new CLASS_6(new ArrayList<CLASS_5>(VAR_21), new CLASS_7[15]);
if(VAR_20){
// Items werden generiert
int[][] VAR_24 = new int[VAR_21][2];
for(int j = 0; j < VAR_24.VAR_5; j++){
VAR_24[j][0] = -1;
VAR_24[j][1] = -1;
}
for(int VAR_6 = 0; VAR_6 < VAR_21; VAR_6++){
int VAR_25;
int VAR_26;
boolean VAR_19 = false;
do {
System.out.FUNC_3("läuft");
// Tiles des Entities werden generiert
VAR_25 = FUNC_7(VAR_0);
VAR_26 = FUNC_7(VAR_1);
// Test, ob Tiles bereits belegt
boolean VAR_27 = true;
for(int j = 0; j < VAR_24.VAR_5; j++){
if(j != VAR_6){
if(VAR_25 == VAR_24[j][0] && VAR_26 == VAR_24[j][1]){
VAR_27 = false;
break;
}
}
}
if(VAR_27 == true){
// Tiles zum Array hinzufügen
for(int j = 0; j < VAR_24.VAR_5; j++){
if(VAR_24[j][0] == -1){
VAR_24[j][0] = VAR_25;
VAR_24[j][1] = VAR_26;
}
}
VAR_19 = true;
}
} while(!VAR_19);
// Berechnung der Positionen
int VAR_11 = VAR_25 * VAR_2;
int VAR_12 = VAR_26 * VAR_2;
// Typ des Entities wird generiert
CLASS_4 VAR_17;
int VAR_28 = (int) (VAR_9.FUNC_2() * 3);
switch(VAR_28){
case 0:
VAR_17 = new IMPORT_4(VAR_7);
break;
case 1:
VAR_17 = new IMPORT_6(VAR_7);
break;
case 2:
VAR_17 = new IMPORT_5(VAR_7);
break;
default:
VAR_17 = null;
}
if(VAR_17 == null){
System.out.FUNC_3("Es gibt Probleme, schau mal beim Raumgenerator nach. Es sind sogar sehr problematische Probleme mit den Items");
}
if(VAR_17 != null){
CLASS_5 VAR_18;
VAR_18 = new CLASS_5(VAR_11, VAR_12, VAR_17);
VAR_23.FUNC_6().add(VAR_18);
}
}
// Entities werden generiert
VAR_24 = new int[VAR_22][2];
for(int j = 0; j < VAR_24.VAR_5; j++){
VAR_24[j][0] = -1;
VAR_24[j][1] = -1;
}
for(int VAR_6 = 0; VAR_6 < VAR_22; VAR_6++){
int VAR_25;
int VAR_26;
boolean VAR_19 = false;
do {
System.out.FUNC_3("läuft");
// Tiles des Entities werden generiert
VAR_25 = FUNC_7(VAR_0);
VAR_26 = FUNC_7(VAR_1);
// Test, ob Tiles bereits belegt
boolean VAR_27 = true;
for(int j = 0; j < VAR_24.VAR_5; j++){
if(j != VAR_6){
if(VAR_25 == VAR_24[j][0] && VAR_26 == VAR_24[j][1]){
VAR_27 = false;
break;
}
}
}
if(VAR_27 == true){
// Tiles zum Array hinzufügen
for(int j = 0; j < VAR_24.VAR_5; j++){
if(VAR_24[j][0] == -1){
VAR_24[j][0] = VAR_25;
VAR_24[j][1] = VAR_26;
}
}
VAR_19 = true;
}
} while(!VAR_19);
// Berechnung der Positionen
int VAR_11 = VAR_25 * VAR_2;
int VAR_12 = VAR_26 * VAR_2;
// Typ des Entities wird generiert
CLASS_7 VAR_29;
int VAR_28 = (int) (VAR_9.FUNC_2() * 16);
switch(VAR_28){
case 0:
VAR_29 = new Archer(VAR_11, VAR_12, VAR_7);
break;
case 1:
VAR_29 = new CLASS_8(VAR_11, VAR_12, VAR_7);
break;
case 2:
VAR_29 = new Wizard(VAR_11, VAR_12, VAR_7);
break;
case 3:
VAR_29 = new CLASS_9(VAR_11, VAR_12, VAR_7);
break;
case 4:
VAR_29 = new CLASS_10(VAR_11, VAR_12, VAR_7);
break;
case 5:
VAR_29 = new CLASS_11(VAR_11, VAR_12, VAR_7);
break;
case 6:
VAR_29 = new CLASS_12(VAR_11, VAR_12, VAR_7);
break;
case 7:
VAR_29 = new Firearcher(VAR_11, VAR_12, VAR_7);
break;
case 8:
VAR_29 = new CLASS_13(VAR_11, VAR_12, VAR_7);
break;
case 9:
VAR_29 = new CLASS_14(VAR_11, VAR_12, VAR_7);
break;
case 10:
VAR_29 = new CLASS_15(VAR_11, VAR_12, VAR_7);
break;
case 11:
//temp = new Healwizard(xPos, yPos, lvl);
/* wird nicht gespawnt
BUG: HP ueber 100%, also crash in HUD container lol
keine Lust zu beheben
--TODO--
*/
VAR_29 = null;
break;
case 12:
VAR_29 = new CLASS_16(VAR_11, VAR_12, VAR_7);
break;
case 13:
VAR_29 = new CLASS_17(VAR_11, VAR_12, VAR_7);
break;
case 14:
VAR_29 = new CLASS_18(VAR_11, VAR_12, VAR_7);
break;
case 15:
VAR_29 = new CLASS_19(VAR_11, VAR_12, VAR_7);
break;
default:
VAR_29 = null;
}
if(VAR_29 == null){
System.out.FUNC_3("Es gibt Probleme, schau mal beim Raumgenerator nach. Es sind sogar sehr problematische Probleme");
}
VAR_23.FUNC_8(VAR_29, VAR_6);
}
}
return VAR_23;
}
private int FUNC_7(int VAR_30){
int VAR_31 = ((int) (VAR_9.FUNC_2() * VAR_30) + 1);
return VAR_31;
}
public void FUNC_9(CLASS_1 VAR_32){
for(int VAR_6=0;VAR_6<VAR_32.FUNC_0().VAR_5;VAR_6++){
CLASS_3 VAR_29 = VAR_32.FUNC_0()[VAR_6];
System.out.FUNC_3("Level " + VAR_6);
for(int j = 0; j < VAR_29.FUNC_5().VAR_5; j++){
for(int VAR_33 = VAR_29.FUNC_5().VAR_5 - 1; VAR_33 >= 0; VAR_33--){
if(VAR_29.FUNC_5()[j][VAR_33] == null){
System.out.print("0 ");
}
else{
System.out.print("1 ");
}
}
System.out.FUNC_3();
}
}
}
}
| 0.832162 | {'IMPORT_0': 'com', 'IMPORT_1': 'model', 'IMPORT_2': 'entities', 'IMPORT_3': 'items', 'IMPORT_4': 'Amulet', 'IMPORT_5': 'DmgAmulet', 'IMPORT_6': 'Potion', 'IMPORT_7': 'Key', 'IMPORT_8': 'java', 'IMPORT_9': 'util', 'CLASS_0': 'DungeonGenerator', 'CLASS_1': 'Dungeon', 'VAR_0': 'sizeX', 'VAR_1': 'sizeY', 'VAR_2': 'tileSize', 'CLASS_2': 'Player', 'VAR_3': 'tempDungeon', 'VAR_4': 'levelAmount', 'FUNC_0': 'getLevel', 'VAR_5': 'length', 'VAR_6': 'i', 'FUNC_1': 'generateLevel', 'CLASS_3': 'Level', 'VAR_7': 'lvl', 'VAR_8': 'roomAmount', 'VAR_9': 'Math', 'FUNC_2': 'random', 'VAR_10': 'tempLevel', 'FUNC_3': 'println', 'VAR_11': 'xPos', 'VAR_12': 'yPos', 'FUNC_4': 'generateRoom', 'VAR_13': 'direction', 'FUNC_5': 'getRooms', 'VAR_14': 'keyRoom', 'VAR_15': 'x', 'VAR_16': 'y', 'CLASS_4': 'Item', 'VAR_17': 'tempItem', 'CLASS_5': 'ItemContainer', 'VAR_18': 'tempContainer', 'FUNC_6': 'getItems', 'VAR_19': 'istFertig', 'CLASS_6': 'Room', 'VAR_20': 'allowEnemies', 'VAR_21': 'itemAmount', 'VAR_22': 'enemyAmount', 'VAR_23': 'tempRoom', 'CLASS_7': 'Entity', 'VAR_24': 'belegt', 'VAR_25': 'xTile', 'VAR_26': 'yTile', 'FUNC_7': 'generateTile', 'VAR_27': 'hatGeklappt', 'VAR_28': 'id', 'VAR_29': 'temp', 'CLASS_8': 'Swordsman', 'CLASS_9': 'Firewizard', 'CLASS_10': 'Earthwizard', 'CLASS_11': 'Fireswordsman', 'CLASS_12': 'Icearcher', 'CLASS_13': 'Iceswordsman', 'CLASS_14': 'Icewizard', 'CLASS_15': 'Waterwizard', 'CLASS_16': 'Naturewizard', 'CLASS_17': 'Darkwizard', 'CLASS_18': 'Darkswordsman', 'CLASS_19': 'Darkarcher', 'FUNC_8': 'setEnemies', 'VAR_30': 'size', 'VAR_31': 'tile', 'FUNC_9': 'ichWillSpielen', 'VAR_32': 'd', 'VAR_33': 'k'} | java | error | 0 |
package net.openid.conformance.fapiciba;
import com.google.gson.JsonObject;
import net.openid.conformance.condition.Condition;
import net.openid.conformance.condition.client.ChangeClientJwksAlgToRS256;
import net.openid.conformance.condition.client.CheckErrorFromTokenEndpointResponseErrorInvalidClient;
import net.openid.conformance.condition.client.CheckTokenEndpointHttpStatusIs400Allowing401ForInvalidClientError;
import net.openid.conformance.testmodule.PublishTestModule;
import net.openid.conformance.util.JWKUtil;
import net.openid.conformance.variant.ClientAuthType;
import net.openid.conformance.variant.VariantNotApplicable;
@PublishTestModule(
testName = "fapi-ciba-id1-ensure-client-assertion-signature-algorithm-in-token-endpoint-request-is-RS256-fails",
displayName = "FAPI-CIBA-ID1: Ensure client_assertion signature algorithm in token endpoint request is RS256 fails",
summary = "This test should end with the token endpoint returning an error message that the client is invalid.",
profile = "FAPI-CIBA-ID1",
configurationFields = {
"server.discoveryUrl",
"client.scope",
"client.jwks",
"client.hint_type",
"client.hint_value",
"mtls.key",
"mtls.cert",
"mtls.ca",
"client2.scope",
"client2.jwks",
"mtls2.key",
"mtls2.cert",
"mtls2.ca",
"resource.resourceUrl"
}
)
@VariantNotApplicable(parameter = ClientAuthType.class, values = { "mtls" })
public class FAPICIBAID1EnsureClientAssertionSignatureAlgorithmInTokenEndpointRequestIsRS256Fails extends AbstractFAPICIBAID1 {
@Override
protected void onConfigure() {
String alg = JWKUtil.getAlgFromClientJwks(env);
if (!alg.equals("PS256")) { // FAPI only allows ES256 and PS256
// This throws an exception: the test will stop here
fireTestSkipped(String.format("This test requires RSA keys to be performed, the alg in client configuration is '%s' so this test is being skipped. If your server does not support PS256 then this will not prevent you certifying.", alg));
}
}
@Override
protected void addClientAuthenticationToTokenEndpointRequest() {
callAndStopOnFailure(ChangeClientJwksAlgToRS256.class, "FAPI-CIBA-7.10");
super.addClientAuthenticationToTokenEndpointRequest();
}
@Override
protected void performPostAuthorizationResponse() {
callTokenEndpointForCibaGrant();
/* If we get an error back from the token endpoint server:
* - It must be a 'invalid_client' error
*/
validateErrorFromTokenEndpointResponse();
callAndContinueOnFailure(CheckTokenEndpointHttpStatusIs400Allowing401ForInvalidClientError.class, Condition.ConditionResult.FAILURE, "RFC6749-5.2", "CIBA-13");
callAndContinueOnFailure(CheckErrorFromTokenEndpointResponseErrorInvalidClient.class, Condition.ConditionResult.FAILURE, "RFC6749-5.2", "CIBA-13");
cleanupAfterBackchannelRequestShouldHaveFailed();
}
@Override
protected void processNotificationCallback(JsonObject requestParts) {
// we've already done the testing; we just approved the authentication so that we don't leave an
// in-progress authentication lying around that would sometime later send an 'expired' ping
fireTestFinished();
}
}
| package net.openid.IMPORT_0.fapiciba;
import IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4;
import net.openid.IMPORT_0.IMPORT_5.IMPORT_6;
import net.openid.IMPORT_0.IMPORT_5.IMPORT_7.IMPORT_8;
import net.openid.IMPORT_0.IMPORT_5.IMPORT_7.CheckErrorFromTokenEndpointResponseErrorInvalidClient;
import net.openid.IMPORT_0.IMPORT_5.IMPORT_7.CheckTokenEndpointHttpStatusIs400Allowing401ForInvalidClientError;
import net.openid.IMPORT_0.IMPORT_9.IMPORT_10;
import net.openid.IMPORT_0.IMPORT_11.JWKUtil;
import net.openid.IMPORT_0.variant.IMPORT_12;
import net.openid.IMPORT_0.variant.IMPORT_13;
@IMPORT_10(
VAR_0 = "fapi-ciba-id1-ensure-client-assertion-signature-algorithm-in-token-endpoint-request-is-RS256-fails",
VAR_1 = "FAPI-CIBA-ID1: Ensure client_assertion signature algorithm in token endpoint request is RS256 fails",
VAR_2 = "This test should end with the token endpoint returning an error message that the client is invalid.",
VAR_3 = "FAPI-CIBA-ID1",
configurationFields = {
"server.discoveryUrl",
"client.scope",
"client.jwks",
"client.hint_type",
"client.hint_value",
"mtls.key",
"mtls.cert",
"mtls.ca",
"client2.scope",
"client2.jwks",
"mtls2.key",
"mtls2.cert",
"mtls2.ca",
"resource.resourceUrl"
}
)
@IMPORT_13(VAR_4 = IMPORT_12.class, VAR_5 = { "mtls" })
public class CLASS_0 extends CLASS_1 {
@Override
protected void FUNC_0() {
CLASS_2 VAR_7 = JWKUtil.FUNC_1(env);
if (!VAR_7.FUNC_2("PS256")) { // FAPI only allows ES256 and PS256
// This throws an exception: the test will stop here
FUNC_3(VAR_6.FUNC_4("This test requires RSA keys to be performed, the alg in client configuration is '%s' so this test is being skipped. If your server does not support PS256 then this will not prevent you certifying.", VAR_7));
}
}
@Override
protected void FUNC_5() {
callAndStopOnFailure(IMPORT_8.class, "FAPI-CIBA-7.10");
super.FUNC_5();
}
@Override
protected void FUNC_6() {
callTokenEndpointForCibaGrant();
/* If we get an error back from the token endpoint server:
* - It must be a 'invalid_client' error
*/
FUNC_7();
FUNC_8(CheckTokenEndpointHttpStatusIs400Allowing401ForInvalidClientError.class, IMPORT_6.VAR_8.FAILURE, "RFC6749-5.2", "CIBA-13");
FUNC_8(CheckErrorFromTokenEndpointResponseErrorInvalidClient.class, IMPORT_6.VAR_8.FAILURE, "RFC6749-5.2", "CIBA-13");
cleanupAfterBackchannelRequestShouldHaveFailed();
}
@Override
protected void FUNC_9(IMPORT_4 VAR_9) {
// we've already done the testing; we just approved the authentication so that we don't leave an
// in-progress authentication lying around that would sometime later send an 'expired' ping
fireTestFinished();
}
}
| 0.734107 | {'IMPORT_0': 'conformance', 'IMPORT_1': 'com', 'IMPORT_2': 'google', 'IMPORT_3': 'gson', 'IMPORT_4': 'JsonObject', 'IMPORT_5': 'condition', 'IMPORT_6': 'Condition', 'IMPORT_7': 'client', 'IMPORT_8': 'ChangeClientJwksAlgToRS256', 'IMPORT_9': 'testmodule', 'IMPORT_10': 'PublishTestModule', 'IMPORT_11': 'util', 'IMPORT_12': 'ClientAuthType', 'IMPORT_13': 'VariantNotApplicable', 'VAR_0': 'testName', 'VAR_1': 'displayName', 'VAR_2': 'summary', 'VAR_3': 'profile', 'VAR_4': 'parameter', 'VAR_5': 'values', 'CLASS_0': 'FAPICIBAID1EnsureClientAssertionSignatureAlgorithmInTokenEndpointRequestIsRS256Fails', 'CLASS_1': 'AbstractFAPICIBAID1', 'FUNC_0': 'onConfigure', 'CLASS_2': 'String', 'VAR_6': 'String', 'VAR_7': 'alg', 'FUNC_1': 'getAlgFromClientJwks', 'FUNC_2': 'equals', 'FUNC_3': 'fireTestSkipped', 'FUNC_4': 'format', 'FUNC_5': 'addClientAuthenticationToTokenEndpointRequest', 'FUNC_6': 'performPostAuthorizationResponse', 'FUNC_7': 'validateErrorFromTokenEndpointResponse', 'FUNC_8': 'callAndContinueOnFailure', 'VAR_8': 'ConditionResult', 'FUNC_9': 'processNotificationCallback', 'VAR_9': 'requestParts'} | java | Procedural | 28.16% |
/**
* Created by geely
*/
public class Adaptee {
public void adapteeRequest(){
System.out.println("被适配者的方法");
}
} | /**
* Created by geely
*/
public class CLASS_0 {
public void FUNC_0(){
System.VAR_0.println("被适配者的方法");
}
} | 0.568202 | {'CLASS_0': 'Adaptee', 'FUNC_0': 'adapteeRequest', 'VAR_0': 'out'} | java | OOP | 100.00% |
/**
* Created by IntelliJ IDEA.
* User: stathik
* Date: Nov 19, 2003
* Time: 10:04:14 PM
* To change this template use Options | File Templates.
*/
public class IOExceptionDialog extends JDialog {
private JPanel mainPanel;
private JButton cancelButton;
private JButton tryAgainButton;
private JButton setupButton;
private JLabel errorLabel;
private boolean cancelPressed = false;
public IOExceptionDialog(String title, String errorText) {
super (JOptionPane.getRootFrame(), title, true);
new MnemonicHelper().register(getContentPane());
getContentPane().add(mainPanel);
//noinspection HardCodedStringLiteral
mainPanel.getActionMap().put(
"close",
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
cancelPressed = true;
dispose();
}
}
);
//noinspection HardCodedStringLiteral
mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),
"close"
);
errorLabel.setText(errorText);
setupButton.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
HTTPProxySettingsDialog dlg = new HTTPProxySettingsDialog();
dlg.show();
}
});
tryAgainButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelPressed = false;
dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelPressed = true;
dispose();
}
});
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Dimension parentSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension ownSize = getPreferredSize();
setLocation((parentSize.width - ownSize.width) / 2, (parentSize.height - ownSize.height) / 2);
pack();
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
cancelPressed = true;
dispose();
}
});
}
/**
* Show
* @return <code>true</code> if "Try Again" button pressed
* @return <code>false</code> if "Cancel" button pressed
*/
public static boolean showErrorDialog(String title, String text) {
final IOExceptionDialog dlg = new IOExceptionDialog(title, text);
try {
final Runnable doRun = new Runnable() {
public void run() {
dlg.setVisible(true);
}
};
GuiUtils.runOrInvokeAndWait(doRun);
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
catch (InvocationTargetException e1) {
e1.printStackTrace();
}
return ! dlg.cancelPressed;
}
} | /**
* Created by IntelliJ IDEA.
* User: stathik
* Date: Nov 19, 2003
* Time: 10:04:14 PM
* To change this template use Options | File Templates.
*/
public class IOExceptionDialog extends JDialog {
private JPanel mainPanel;
private JButton cancelButton;
private JButton tryAgainButton;
private JButton setupButton;
private JLabel errorLabel;
private boolean cancelPressed = false;
public IOExceptionDialog(String title, String errorText) {
super (JOptionPane.getRootFrame(), title, true);
new MnemonicHelper().register(FUNC_0());
FUNC_0().add(mainPanel);
//noinspection HardCodedStringLiteral
mainPanel.getActionMap().put(
"close",
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
cancelPressed = true;
dispose();
}
}
);
//noinspection HardCodedStringLiteral
mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),
"close"
);
errorLabel.setText(errorText);
setupButton.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
HTTPProxySettingsDialog dlg = new HTTPProxySettingsDialog();
dlg.show();
}
});
tryAgainButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelPressed = false;
dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelPressed = true;
dispose();
}
});
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Dimension parentSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension ownSize = getPreferredSize();
setLocation((parentSize.width - ownSize.width) / 2, (parentSize.height - ownSize.height) / 2);
pack();
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(CLASS_0 e) {
cancelPressed = true;
dispose();
}
});
}
/**
* Show
* @return <code>true</code> if "Try Again" button pressed
* @return <code>false</code> if "Cancel" button pressed
*/
public static boolean showErrorDialog(String title, String text) {
final IOExceptionDialog dlg = new IOExceptionDialog(title, text);
try {
final Runnable doRun = new Runnable() {
public void run() {
dlg.setVisible(true);
}
};
GuiUtils.runOrInvokeAndWait(doRun);
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
catch (InvocationTargetException e1) {
e1.printStackTrace();
}
return ! dlg.cancelPressed;
}
} | 0.059855 | {'FUNC_0': 'getContentPane', 'CLASS_0': 'WindowEvent'} | java | OOP | 15.70% |
package tratamentoerroteclado;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TratamentoErroTeclado {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try{
System.out.print("Digite a idade: ");
int idade = sc.nextInt();
System.out.println(idade);
} catch (InputMismatchException e) {
System.out.println("Um Erro ocorreu!");
System.out.println("A seguir encontra-se a arvore de execução.");
e.printStackTrace();
}
}
}
| package tratamentoerroteclado;
import IMPORT_0.util.InputMismatchException;
import IMPORT_0.util.Scanner;
public class TratamentoErroTeclado {
public static void main(CLASS_0[] VAR_0) {
Scanner sc = new Scanner(VAR_1.in);
try{
VAR_1.VAR_2.print("Digite a idade: ");
int VAR_3 = sc.FUNC_0();
VAR_1.VAR_2.FUNC_1(VAR_3);
} catch (InputMismatchException e) {
VAR_1.VAR_2.FUNC_1("Um Erro ocorreu!");
VAR_1.VAR_2.FUNC_1("A seguir encontra-se a arvore de execução.");
e.printStackTrace();
}
}
}
| 0.372973 | {'IMPORT_0': 'java', 'CLASS_0': 'String', 'VAR_0': 'args', 'VAR_1': 'System', 'VAR_2': 'out', 'VAR_3': 'idade', 'FUNC_0': 'nextInt', 'FUNC_1': 'println'} | java | OOP | 100.00% |
package ufc.config;
import javax.sql.DataSource;
import ufc.constants.Configuration_M;
import ufc.constants.Urls;
import ufc.spring.AuthenticationTokenProcessingFilter;
import ufc.spring.CustomUserDetailsService;
import ufc.spring.SuccessHandler;
import ufc.spring.UnauthorizedEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
private static final String USERS_BY_USERNAME_QUERY =
"select username, password, true from users where username = ?";
private static final String AUTHORITIES_BY_USERNAME_QUERY =
"select username, authority from authorities where username = ?";
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.userDetailsService(userDetailsService())
.and()
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(USERS_BY_USERNAME_QUERY)
.authoritiesByUsernameQuery(AUTHORITIES_BY_USERNAME_QUERY);
// @formatter:on
}
//
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilterBefore(authenticationTokenProcessingFilter(), BasicAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(unauthorizedEntryPoint())
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers(Configuration_M.ACTION.concat(Urls.AUTHENTICATE)).permitAll()
.antMatchers(Configuration_M.ACTION.concat(Urls.DDOS).concat("/**")).permitAll()
.antMatchers("/*").permitAll()
.antMatchers(Configuration_M.PUBLIC_HTML).permitAll()
.antMatchers(Configuration_M.HTML_TEMPLATES).permitAll()
// .antMatchers(Urls.AUTHENTICATE.concat("**")).permitAll()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().disable()
// .loginPage("/login.html").permitAll()
// .loginProcessingUrl("/login").disable()
// .successHandler(successHandler())
// .and()
.logout()
.logoutUrl("/logout").permitAll()
.logoutSuccessUrl("/")
.deleteCookies(Configuration_M.AUTH_TOKEN);
// @formatter:on
}
//
@Bean
@Override
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
@Bean
public UnauthorizedEntryPoint unauthorizedEntryPoint() {
return new UnauthorizedEntryPoint();
}
@Bean
public AuthenticationTokenProcessingFilter authenticationTokenProcessingFilter() {
return new AuthenticationTokenProcessingFilter(userDetailsService());
}
@Bean
public SuccessHandler successHandler() {
return new SuccessHandler();
}
@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
| package ufc.config;
import javax.sql.DataSource;
import ufc.constants.Configuration_M;
import ufc.constants.Urls;
import ufc.spring.AuthenticationTokenProcessingFilter;
import ufc.spring.CustomUserDetailsService;
import ufc.spring.SuccessHandler;
import ufc.spring.UnauthorizedEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
private static final String USERS_BY_USERNAME_QUERY =
"select username, password, true from users where username = ?";
private static final String AUTHORITIES_BY_USERNAME_QUERY =
"select username, authority from authorities where username = ?";
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.userDetailsService(userDetailsService())
.and()
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(USERS_BY_USERNAME_QUERY)
.authoritiesByUsernameQuery(AUTHORITIES_BY_USERNAME_QUERY);
// @formatter:on
}
//
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilterBefore(authenticationTokenProcessingFilter(), BasicAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(unauthorizedEntryPoint())
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers(Configuration_M.ACTION.concat(Urls.AUTHENTICATE)).permitAll()
.antMatchers(Configuration_M.ACTION.concat(Urls.DDOS).concat("/**")).permitAll()
.antMatchers("/*").permitAll()
.antMatchers(Configuration_M.PUBLIC_HTML).permitAll()
.antMatchers(Configuration_M.HTML_TEMPLATES).permitAll()
// .antMatchers(Urls.AUTHENTICATE.concat("**")).permitAll()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().disable()
// .loginPage("/login.html").permitAll()
// .loginProcessingUrl("/login").disable()
// .successHandler(successHandler())
// .and()
.logout()
.logoutUrl("/logout").permitAll()
.logoutSuccessUrl("/")
.deleteCookies(Configuration_M.AUTH_TOKEN);
// @formatter:on
}
//
@Bean
@Override
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
@Bean
public UnauthorizedEntryPoint unauthorizedEntryPoint() {
return new UnauthorizedEntryPoint();
}
@Bean
public AuthenticationTokenProcessingFilter authenticationTokenProcessingFilter() {
return new AuthenticationTokenProcessingFilter(userDetailsService());
}
@Bean
public SuccessHandler successHandler() {
return new SuccessHandler();
}
@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
| 0.019549 | {} | java | OOP | 35.85% |
package com.thread.schedule;
import java.util.Date;
import java.util.concurrent.Callable;
import com.thread.SleepUtils;
public class Task implements /*Callable<String>*/ Runnable{
private String name;
public Task(String name){
this.name = name;
}
@Override
public void run() {
System.out.printf("%s Starting at : %s \n",name,new Date());
SleepUtils.second(100);
System.out.printf("%s Ending at : %s \n",name,new Date());
}
/* @Override
public String call() throws Exception {
System.out.printf("%s Starting at : %s \n",name,new Date());
return "hello,world! "+name;
}*/
}
| package IMPORT_0.IMPORT_1.IMPORT_2;
import IMPORT_3.IMPORT_4.IMPORT_5;
import IMPORT_3.IMPORT_4.IMPORT_6.IMPORT_7;
import IMPORT_0.IMPORT_1.IMPORT_8;
public class CLASS_0 implements /*Callable<String>*/ CLASS_1{
private CLASS_2 VAR_0;
public CLASS_0(CLASS_2 VAR_0){
this.VAR_0 = VAR_0;
}
@VAR_1
public void FUNC_0() {
VAR_2.VAR_3.FUNC_1("%s Starting at : %s \n",VAR_0,new IMPORT_5());
IMPORT_8.FUNC_2(100);
VAR_2.VAR_3.FUNC_1("%s Ending at : %s \n",VAR_0,new IMPORT_5());
}
/* @Override
public String call() throws Exception {
System.out.printf("%s Starting at : %s \n",name,new Date());
return "hello,world! "+name;
}*/
}
| 0.984521 | {'IMPORT_0': 'com', 'IMPORT_1': 'thread', 'IMPORT_2': 'schedule', 'IMPORT_3': 'java', 'IMPORT_4': 'util', 'IMPORT_5': 'Date', 'IMPORT_6': 'concurrent', 'IMPORT_7': 'Callable', 'IMPORT_8': 'SleepUtils', 'CLASS_0': 'Task', 'CLASS_1': 'Runnable', 'CLASS_2': 'String', 'VAR_0': 'name', 'VAR_1': 'Override', 'FUNC_0': 'run', 'VAR_2': 'System', 'VAR_3': 'out', 'FUNC_1': 'printf', 'FUNC_2': 'second'} | java | OOP | 57.45% |
/**
*
*
* Retry any pending patch sync operations.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createNodesNodePatchSyncItemTest() throws ApiException {
Empty nodesNodePatchSyncItem = null;
Integer lnn = null;
Empty response = api.createNodesNodePatchSyncItem(nodesNodePatchSyncItem, lnn);
} | /**
*
*
* Retry any pending patch sync operations.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void FUNC_0() throws CLASS_0 {
Empty nodesNodePatchSyncItem = null;
Integer VAR_0 = null;
Empty VAR_1 = VAR_2.FUNC_1(nodesNodePatchSyncItem, VAR_0);
} | 0.661507 | {'FUNC_0': 'createNodesNodePatchSyncItemTest', 'CLASS_0': 'ApiException', 'VAR_0': 'lnn', 'VAR_1': 'response', 'VAR_2': 'api', 'FUNC_1': 'createNodesNodePatchSyncItem'} | java | Procedural | 59.46% |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br1 = new BufferedReader(
new InputStreamReader(System.in));
String[] data = br1.readLine().split(" ");
long x = Long.parseLong(data[0]);
long y = Long.parseLong(data[1]);
long x1=-1,y1=-1;
long c;
if ((x > 0 && y > 0) ) {
c = y +x;
y1 =c;
x1= c;
}
else if((x<0 && y<0))
{
c = y +x;
y1 =c;
x1= c;
}
else if(x>0 && y<0)
{
c = y-x;
y1 = c;
x1 = 0-c;
}
else {
c = y-x;
y1 = c;
x1 = 0-c;
}
if(x1>=0)
{
System.out.println("0 "+y1+" "+x1+" 0");
}
else{
System.out.println(x1+" 0 0 "+y1);
}
}
}
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader VAR_0 = new BufferedReader(
new InputStreamReader(System.in));
String[] data = VAR_0.FUNC_0().split(" ");
long x = Long.parseLong(data[0]);
long y = Long.parseLong(data[1]);
long x1=-1,y1=-1;
long c;
if ((x > 0 && y > 0) ) {
c = y +x;
y1 =c;
x1= c;
}
else if((x<0 && y<0))
{
c = y +x;
y1 =c;
x1= c;
}
else if(x>0 && y<0)
{
c = y-x;
y1 = c;
x1 = 0-c;
}
else {
c = y-x;
y1 = c;
x1 = 0-c;
}
if(x1>=0)
{
System.out.println("0 "+y1+" "+x1+" 0");
}
else{
System.out.println(x1+" 0 0 "+y1);
}
}
}
| 0.081609 | {'VAR_0': 'br1', 'FUNC_0': 'readLine'} | java | OOP | 23.33% |
package com.aiprof.alena.get_gps_from_sms;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.example.alena.sms_gps_30.R;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
public class FragmentSendLogs extends Fragment {
private OnFragmentInteractionListener mListener;
private final String TAG = ActivityMap.TAG + " logFragm";
EditText editTextMessageForDev, editTextMesageInLogs;
Button buttonSendLogs, buttonSaveInLogs;
onSomeEventListener someEventListener;
public interface onSomeEventListener {
public void someEvent(String s);
}
public FragmentSendLogs() {
// Required empty public constructor
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
someEventListener = (FragmentSendLogs.onSomeEventListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_send_logs, container, false);
editTextMesageInLogs = (EditText) view.findViewById(R.id.editTextMessageLogs);
buttonSaveInLogs = (Button) view.findViewById(R.id.buttonMessageLogs);
buttonSaveInLogs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveFile(editTextMesageInLogs.getText().toString());
editTextMesageInLogs.setText("");
Toast.makeText(getActivity(), "Сообщение успешно добавлено", Toast.LENGTH_SHORT).show();
}
});
editTextMessageForDev = (EditText) view.findViewById(R.id.editTextLogs);
buttonSendLogs = (Button) view.findViewById(R.id.buttonSendLogs);
buttonSendLogs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RequestTask requestTask = new RequestTask();
requestTask.execute(editTextMessageForDev.getText().toString());
}
});
ImageButton buttonBack = (ImageButton) view.findViewById(R.id.imageButtonBack);
buttonBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopSelf();
}
});
return view;
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void stopSelf(){
someEventListener.someEvent("end");
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(0, R.animator.fragment_exit);
ft.remove(this);
ft.commit();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
class RequestTask extends AsyncTask<String,Void,String>{
String lineAnswer = "";
public RequestTask() {
}
@Override
protected String doInBackground(String... params) {
StringBuilder builder = null;
File gpxfile = null;
try {
//читать
File file = new File(getActivity().getFilesDir(), "LOGS");
gpxfile = new File(file, ServiceIntentSaveLOGs.FILE_NAME);
FileReader fileReader1 = new FileReader(gpxfile);
BufferedReader reader = new BufferedReader(fileReader1);
String line;
builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
fileReader1.close();
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, e.toString());
cancel(true);
}
//отправить
try {
HttpURLConnection connection = null;
if (builder != null) {
String encodedQueryVersion = URLEncoder.encode(getVersion(), "UTF-8");
String encodedQueryInfo = URLEncoder.encode(getIdTelephone(), "UTF-8");
String encodedQueryData = URLEncoder.encode(builder.toString(), "UTF-8");
String encodedQueryMessage = URLEncoder.encode(params[0], "UTF-8");
String postData = "{\"version\":\"" + encodedQueryVersion +
"\",\"info\":\""+encodedQueryInfo+
"\",\"data\":\""+ encodedQueryData +
"\",\"message\":\"" + encodedQueryMessage + "\"}";
URL url = new URL("http://gps.aiprof.ru/data.php");
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", String.valueOf(postData.length()));
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
os.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer sb = new StringBuffer("");
while((lineAnswer = in.readLine()) != null) {
sb.append(lineAnswer);
break;
}
in.close();
if (lineAnswer.equals("ok")){
gpxfile.delete(); //очистить логи если отправка успешная
}
Log.d(TAG, "lineAnswer: " + sb.toString());
}
else {
Log.d(TAG, "false : " + responseCode);
}
}
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, e.toString());
}
return lineAnswer;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s.equals("ok")){
Toast.makeText(getActivity(), "логи успешно отправлены", Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), "Спасибо за участие!", Toast.LENGTH_SHORT).show();
editTextMessageForDev.setText("");
} else {
if (!isOnline(getActivity())){
Toast.makeText(getActivity(), "нет подключения к интернету", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onCancelled(String s) {
super.onCancelled(s);
Toast.makeText(getActivity(), "логи пусты", Toast.LENGTH_SHORT).show();
}
}
private String getVersion(){
SharedPreferences sPref = getActivity().getSharedPreferences(ActivityMap.APP_PREFERENCES, Context.MODE_PRIVATE);
return sPref.getString(ActivityMap.VERSION, "0");
}
private String getIdTelephone(){
TelephonyManager telephonyManager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = telephonyManager.getLine1Number();
return phoneNumber;
}
public static boolean isOnline(Context context)
{
ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnectedOrConnecting());
}
private void saveFile(String text) {
Intent logsIntent = new Intent(getActivity(), ServiceIntentSaveLOGs.class);
logsIntent.putExtra(ServiceIntentSaveLOGs.TIME_LOGS, System.currentTimeMillis());
logsIntent.putExtra(ServiceIntentSaveLOGs.TEXT_LOGS, text);
getActivity().startService(logsIntent);
}
}
| package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3;
import IMPORT_4.IMPORT_5.IMPORT_6;
import IMPORT_4.IMPORT_5.IMPORT_7;
import IMPORT_4.IMPORT_8.IMPORT_9;
import IMPORT_4.IMPORT_8.IMPORT_10;
import IMPORT_4.IMPORT_8.IMPORT_11;
import IMPORT_4.IMPORT_12.IMPORT_13;
import IMPORT_4.IMPORT_12.IMPORT_14;
import IMPORT_4.IMPORT_12.IMPORT_15;
import IMPORT_4.IMPORT_16.IMPORT_17;
import IMPORT_4.IMPORT_16.IMPORT_18;
import IMPORT_4.IMPORT_5.IMPORT_19;
import IMPORT_4.IMPORT_20.IMPORT_21;
import IMPORT_4.util.IMPORT_22;
import IMPORT_4.IMPORT_23.IMPORT_24;
import IMPORT_4.IMPORT_23.IMPORT_25;
import IMPORT_4.IMPORT_23.IMPORT_26;
import IMPORT_4.IMPORT_27.IMPORT_28;
import IMPORT_4.IMPORT_27.IMPORT_29;
import IMPORT_4.IMPORT_27.IMPORT_30;
import IMPORT_4.IMPORT_27.IMPORT_31;
import IMPORT_0.IMPORT_32.IMPORT_2.IMPORT_33.IMPORT_34;
import java.IMPORT_35.BufferedReader;
import java.IMPORT_35.IMPORT_36;
import java.IMPORT_35.IMPORT_37;
import java.IMPORT_35.IMPORT_38;
import java.IMPORT_35.IMPORT_39;
import java.IMPORT_35.IMPORT_40;
import java.IMPORT_12.HttpURLConnection;
import java.IMPORT_12.IMPORT_41;
import java.IMPORT_12.IMPORT_42;
import IMPORT_43.IMPORT_12.IMPORT_44.IMPORT_45;
public class CLASS_0 extends IMPORT_19 {
private CLASS_1 VAR_0;
private final CLASS_2 VAR_2 = VAR_3.VAR_2 + " logFragm";
IMPORT_29 VAR_4, VAR_5;
IMPORT_28 VAR_6, VAR_7;
CLASS_3 VAR_8;
public interface CLASS_3 {
public void FUNC_0(CLASS_2 VAR_9);
}
public CLASS_0() {
// Required empty public constructor
}
@VAR_10
public void FUNC_1(IMPORT_6 VAR_11) {
super.FUNC_1(VAR_11);
try {
VAR_8 = (CLASS_0.CLASS_3) VAR_11;
} catch (CLASS_4 VAR_12) {
throw new CLASS_4(VAR_11.FUNC_2() + " must implement onSomeEventListener");
}
}
@VAR_10
public void FUNC_3(IMPORT_18 VAR_13) {
super.FUNC_3(VAR_13);
}
@VAR_10
public IMPORT_25 FUNC_4(IMPORT_24 VAR_14, IMPORT_26 VAR_15,
IMPORT_18 VAR_13) {
// Inflate the layout for this fragment
IMPORT_25 IMPORT_23 = VAR_14.FUNC_5(IMPORT_34.VAR_16.VAR_17, VAR_15, false);
VAR_5 = (IMPORT_29) IMPORT_23.FUNC_6(IMPORT_34.VAR_18.editTextMessageLogs);
VAR_7 = (IMPORT_28) IMPORT_23.FUNC_6(IMPORT_34.VAR_18.VAR_19);
VAR_7.FUNC_7(new IMPORT_25.CLASS_5() {
@VAR_10
public void FUNC_8(IMPORT_25 VAR_20) {
FUNC_9(VAR_5.FUNC_10().FUNC_2());
VAR_5.FUNC_11("");
IMPORT_31.FUNC_12(FUNC_13(), "Сообщение успешно добавлено", Toast.LENGTH_SHORT).show();
}
});
VAR_4 = (IMPORT_29) IMPORT_23.FUNC_6(IMPORT_34.VAR_18.VAR_21);
VAR_6 = (IMPORT_28) IMPORT_23.FUNC_6(IMPORT_34.VAR_18.VAR_6);
VAR_6.FUNC_7(new IMPORT_25.CLASS_5() {
@VAR_10
public void FUNC_8(IMPORT_25 VAR_20) {
CLASS_6 VAR_22 = new CLASS_6();
VAR_22.FUNC_14(VAR_4.FUNC_10().FUNC_2());
}
});
IMPORT_30 VAR_23 = (IMPORT_30) IMPORT_23.FUNC_6(IMPORT_34.VAR_18.VAR_24);
VAR_23.FUNC_7(new IMPORT_25.CLASS_5() {
@VAR_10
public void FUNC_8(IMPORT_25 VAR_20) {
FUNC_15();
}
});
return IMPORT_23;
}
@VAR_10
public void FUNC_16() {
super.FUNC_16();
VAR_0 = null;
}
private void FUNC_15(){
VAR_8.FUNC_0("end");
IMPORT_7 VAR_25 = FUNC_17().FUNC_18();
VAR_25.FUNC_19(0, IMPORT_34.VAR_26.VAR_27);
VAR_25.FUNC_20(this);
VAR_25.FUNC_21();
}
public interface CLASS_1 {
// TODO: Update argument type and name
void FUNC_22(IMPORT_15 VAR_28);
}
class CLASS_6 extends IMPORT_17<CLASS_2,CLASS_7,CLASS_2>{
CLASS_2 VAR_29 = "";
public CLASS_6() {
}
@VAR_10
protected CLASS_2 FUNC_23(CLASS_2... VAR_30) {
CLASS_8 VAR_31 = null;
IMPORT_36 VAR_32 = null;
try {
//читать
IMPORT_36 VAR_33 = new IMPORT_36(FUNC_13().FUNC_24(), "LOGS");
VAR_32 = new IMPORT_36(VAR_33, VAR_34.VAR_35);
IMPORT_37 VAR_36 = new IMPORT_37(VAR_32);
BufferedReader VAR_37 = new BufferedReader(VAR_36);
CLASS_2 VAR_38;
VAR_31 = new CLASS_8();
while ((VAR_38 = VAR_37.FUNC_25()) != null) {
VAR_31.FUNC_26(VAR_38 + "\n");
}
VAR_36.FUNC_27();
} catch (IMPORT_38 VAR_12) {
VAR_12.printStackTrace();
IMPORT_22.d(VAR_2, VAR_12.FUNC_2());
FUNC_28(true);
}
//отправить
try {
HttpURLConnection VAR_39 = null;
if (VAR_31 != null) {
CLASS_2 VAR_40 = IMPORT_42.FUNC_29(FUNC_30(), "UTF-8");
CLASS_2 VAR_41 = IMPORT_42.FUNC_29(FUNC_31(), "UTF-8");
CLASS_2 VAR_42 = IMPORT_42.FUNC_29(VAR_31.FUNC_2(), "UTF-8");
CLASS_2 VAR_43 = IMPORT_42.FUNC_29(VAR_30[0], "UTF-8");
CLASS_2 VAR_44 = "{\"version\":\"" + VAR_40 +
"\",\"info\":\""+VAR_41+
"\",\"data\":\""+ VAR_42 +
"\",\"message\":\"" + VAR_43 + "\"}";
IMPORT_41 VAR_45 = new IMPORT_41("http://gps.aiprof.ru/data.php");
VAR_39 = (HttpURLConnection)VAR_45.FUNC_32();
VAR_39.FUNC_33(true);
VAR_39.FUNC_34("POST");
VAR_39.FUNC_35("Content-Type", "application/json");
VAR_39.FUNC_35("Content-Length", VAR_1.FUNC_36(VAR_44.FUNC_37()));
IMPORT_40 IMPORT_16 = VAR_39.FUNC_38();
IMPORT_16.FUNC_39(VAR_44.FUNC_40());
IMPORT_16.FUNC_27();
int VAR_46 = VAR_39.FUNC_41();
if (VAR_46 == IMPORT_45.VAR_47) {
BufferedReader VAR_48 = new BufferedReader(new IMPORT_39(VAR_39.FUNC_42()));
CLASS_10 VAR_49 = new CLASS_10("");
while((VAR_29 = VAR_48.FUNC_25()) != null) {
VAR_49.FUNC_26(VAR_29);
break;
}
VAR_48.FUNC_27();
if (VAR_29.equals("ok")){
VAR_32.FUNC_43(); //очистить логи если отправка успешная
}
IMPORT_22.d(VAR_2, "lineAnswer: " + VAR_49.FUNC_2());
}
else {
IMPORT_22.d(VAR_2, "false : " + VAR_46);
}
}
} catch (IMPORT_38 VAR_12) {
VAR_12.printStackTrace();
IMPORT_22.d(VAR_2, VAR_12.FUNC_2());
}
return VAR_29;
}
@VAR_10
protected void FUNC_44(CLASS_2 VAR_9) {
super.FUNC_44(VAR_9);
if (VAR_9.equals("ok")){
IMPORT_31.FUNC_12(FUNC_13(), "логи успешно отправлены", Toast.LENGTH_SHORT).sVAR_50;
IMPORT_31.FUNC_12(FUNC_13(), "Спасибо за участие!", Toast.LENGTH_SHOVAR_51how();
VAR_4.FUNC_11("");
} else {
if (!FUNC_45(FUNC_13())){
IMPORT_31.FUNC_12(FUNC_13(), "нет подключения к интернету", Toast.LENGTH_SHORT).show();
}
}
}
@VAR_10
protected void FUNC_46(CLASS_2 VAR_9) {
super.FUNC_46(VAR_9);
IMPORT_31.FUNC_12(FUNC_13(), "логи пусты", Toast.LENVAR_52HVAR_53
}
}
private CLASS_2 FUNC_30(){
IMPORT_11 VAR_54 = FUNC_13().FUNC_47(VAR_3.VAR_55, IMPORT_9.VAR_56);
return VAR_54.FUNC_48(VAR_3.VAR_57, "0");
}
private CLASS_2 FUNC_31(){
IMPORT_21 VAR_58 = (IMPORT_21) FUNC_13().FUNC_49(IMPORT_9.VAR_59);
CLASS_2 VAR_60 = VAR_58.FUNC_50();
return VAR_60;
}
public static boolean FUNC_45(IMPORT_9 VAR_61)
{
IMPORT_13 VAR_62 =(IMPORT_13) VAR_61.FUNC_49(IMPORT_9.VAR_63);
IMPORT_14 VAR_64 = VAR_62.FUNC_51();
return (VAR_64 != null && VAR_64.FUNC_52());
}
private void FUNC_9(CLASS_2 VAR_65) {
IMPORT_10 VAR_66 = new IMPORT_10(FUNC_13(), CLASS_9.class);
VAR_66.FUNC_53(VAR_34.VAR_67, VAR_68.FUNC_54());
VAR_66.FUNC_53(VAR_34.VAR_69, VAR_65);
FUNC_13().FUNC_55(VAR_66);
}
}
| 0.958011 | {'IMPORT_0': 'com', 'IMPORT_1': 'aiprof', 'IMPORT_2': 'alena', 'IMPORT_3': 'get_gps_from_sms', 'IMPORT_4': 'android', 'IMPORT_5': 'app', 'IMPORT_6': 'Activity', 'IMPORT_7': 'FragmentTransaction', 'IMPORT_8': 'content', 'IMPORT_9': 'Context', 'IMPORT_10': 'Intent', 'IMPORT_11': 'SharedPreferences', 'IMPORT_12': 'net', 'IMPORT_13': 'ConnectivityManager', 'IMPORT_14': 'NetworkInfo', 'IMPORT_15': 'Uri', 'IMPORT_16': 'os', 'IMPORT_17': 'AsyncTask', 'IMPORT_18': 'Bundle', 'IMPORT_19': 'Fragment', 'IMPORT_20': 'telephony', 'IMPORT_21': 'TelephonyManager', 'IMPORT_22': 'Log', 'IMPORT_23': 'view', 'IMPORT_24': 'LayoutInflater', 'IMPORT_25': 'View', 'IMPORT_26': 'ViewGroup', 'IMPORT_27': 'widget', 'IMPORT_28': 'Button', 'IMPORT_29': 'EditText', 'IMPORT_30': 'ImageButton', 'IMPORT_31': 'Toast', 'IMPORT_32': 'example', 'IMPORT_33': 'sms_gps_30', 'IMPORT_34': 'R', 'IMPORT_35': 'io', 'IMPORT_36': 'File', 'IMPORT_37': 'FileReader', 'IMPORT_38': 'IOException', 'IMPORT_39': 'InputStreamReader', 'IMPORT_40': 'OutputStream', 'IMPORT_41': 'URL', 'IMPORT_42': 'URLEncoder', 'IMPORT_43': 'javax', 'IMPORT_44': 'ssl', 'IMPORT_45': 'HttpsURLConnection', 'CLASS_0': 'FragmentSendLogs', 'CLASS_1': 'OnFragmentInteractionListener', 'VAR_0': 'mListener', 'CLASS_2': 'String', 'VAR_1': 'String', 'VAR_2': 'TAG', 'VAR_3': 'ActivityMap', 'VAR_4': 'editTextMessageForDev', 'VAR_5': 'editTextMesageInLogs', 'VAR_6': 'buttonSendLogs', 'VAR_7': 'buttonSaveInLogs', 'CLASS_3': 'onSomeEventListener', 'VAR_8': 'someEventListener', 'FUNC_0': 'someEvent', 'VAR_9': 's', 'VAR_10': 'Override', 'FUNC_1': 'onAttach', 'VAR_11': 'activity', 'CLASS_4': 'ClassCastException', 'VAR_12': 'e', 'FUNC_2': 'toString', 'FUNC_3': 'onCreate', 'VAR_13': 'savedInstanceState', 'FUNC_4': 'onCreateView', 'VAR_14': 'inflater', 'VAR_15': 'container', 'FUNC_5': 'inflate', 'VAR_16': 'layout', 'VAR_17': 'fragment_send_logs', 'FUNC_6': 'findViewById', 'VAR_18': 'id', 'VAR_19': 'buttonMessageLogs', 'FUNC_7': 'setOnClickListener', 'CLASS_5': 'OnClickListener', 'FUNC_8': 'onClick', 'VAR_20': 'v', 'FUNC_9': 'saveFile', 'FUNC_10': 'getText', 'FUNC_11': 'setText', 'FUNC_12': 'makeText', 'FUNC_13': 'getActivity', 'VAR_21': 'editTextLogs', 'CLASS_6': 'RequestTask', 'VAR_22': 'requestTask', 'FUNC_14': 'execute', 'VAR_23': 'buttonBack', 'VAR_24': 'imageButtonBack', 'FUNC_15': 'stopSelf', 'FUNC_16': 'onDetach', 'VAR_25': 'ft', 'FUNC_17': 'getFragmentManager', 'FUNC_18': 'beginTransaction', 'FUNC_19': 'setCustomAnimations', 'VAR_26': 'animator', 'VAR_27': 'fragment_exit', 'FUNC_20': 'remove', 'FUNC_21': 'commit', 'FUNC_22': 'onFragmentInteraction', 'VAR_28': 'uri', 'CLASS_7': 'Void', 'VAR_29': 'lineAnswer', 'FUNC_23': 'doInBackground', 'VAR_30': 'params', 'CLASS_8': 'StringBuilder', 'VAR_31': 'builder', 'VAR_32': 'gpxfile', 'VAR_33': 'file', 'FUNC_24': 'getFilesDir', 'VAR_34': 'ServiceIntentSaveLOGs', 'CLASS_9': 'ServiceIntentSaveLOGs', 'VAR_35': 'FILE_NAME', 'VAR_36': 'fileReader1', 'VAR_37': 'reader', 'VAR_38': 'line', 'FUNC_25': 'readLine', 'FUNC_26': 'append', 'FUNC_27': 'close', 'FUNC_28': 'cancel', 'VAR_39': 'connection', 'VAR_40': 'encodedQueryVersion', 'FUNC_29': 'encode', 'FUNC_30': 'getVersion', 'VAR_41': 'encodedQueryInfo', 'FUNC_31': 'getIdTelephone', 'VAR_42': 'encodedQueryData', 'VAR_43': 'encodedQueryMessage', 'VAR_44': 'postData', 'VAR_45': 'url', 'FUNC_32': 'openConnection', 'FUNC_33': 'setDoOutput', 'FUNC_34': 'setRequestMethod', 'FUNC_35': 'setRequestProperty', 'FUNC_36': 'valueOf', 'FUNC_37': 'length', 'FUNC_38': 'getOutputStream', 'FUNC_39': 'write', 'FUNC_40': 'getBytes', 'VAR_46': 'responseCode', 'FUNC_41': 'getResponseCode', 'VAR_47': 'HTTP_OK', 'VAR_48': 'in', 'FUNC_42': 'getInputStream', 'CLASS_10': 'StringBuffer', 'VAR_49': 'sb', 'FUNC_43': 'delete', 'FUNC_44': 'onPostExecute', 'VAR_50': 'how()', 'VAR_51': 'RT).s', 'FUNC_45': 'isOnline', 'FUNC_46': 'onCancelled', 'VAR_52': 'GTH_S', 'VAR_53': 'ORT).show();', 'VAR_54': 'sPref', 'FUNC_47': 'getSharedPreferences', 'VAR_55': 'APP_PREFERENCES', 'VAR_56': 'MODE_PRIVATE', 'FUNC_48': 'getString', 'VAR_57': 'VERSION', 'VAR_58': 'telephonyManager', 'FUNC_49': 'getSystemService', 'VAR_59': 'TELEPHONY_SERVICE', 'VAR_60': 'phoneNumber', 'FUNC_50': 'getLine1Number', 'VAR_61': 'context', 'VAR_62': 'cm', 'VAR_63': 'CONNECTIVITY_SERVICE', 'VAR_64': 'netInfo', 'FUNC_51': 'getActiveNetworkInfo', 'FUNC_52': 'isConnectedOrConnecting', 'VAR_65': 'text', 'VAR_66': 'logsIntent', 'FUNC_53': 'putExtra', 'VAR_67': 'TIME_LOGS', 'VAR_68': 'System', 'FUNC_54': 'currentTimeMillis', 'VAR_69': 'TEXT_LOGS', 'FUNC_55': 'startService'} | java | error | 0 |
/**
* Unlock only if the current thread is the owner.
*
* @param lock
*/
public void unlock(LockImpl lock) {
if (lock.isOwner() && lock.isLocked()) {
if (debug) {
LOGGER.debug(Thread.currentThread() + " unlocked " + lock.getLocked());
}
lock.setLocked(false);
synchronized (monitor) {
lockMap.remove(lock.getLocked());
}
}
} | /**
* Unlock only if the current thread is the owner.
*
* @param lock
*/
public void FUNC_0(CLASS_0 VAR_0) {
if (VAR_0.FUNC_1() && VAR_0.FUNC_2()) {
if (VAR_1) {
VAR_2.FUNC_3(Thread.FUNC_4() + " unlocked " + VAR_0.getLocked());
}
VAR_0.FUNC_5(false);
synchronized (VAR_3) {
lockMap.FUNC_6(VAR_0.getLocked());
}
}
} | 0.881873 | {'FUNC_0': 'unlock', 'CLASS_0': 'LockImpl', 'VAR_0': 'lock', 'FUNC_1': 'isOwner', 'FUNC_2': 'isLocked', 'VAR_1': 'debug', 'FUNC_3': 'debug', 'VAR_2': 'LOGGER', 'FUNC_4': 'currentThread', 'FUNC_5': 'setLocked', 'VAR_3': 'monitor', 'FUNC_6': 'remove'} | java | Procedural | 34.29% |
/*
* Copyright (c) 2018 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* 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.tanrabad.survey.presenter.authen.appauth;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.MainThread;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import net.openid.appauth.AppAuthConfiguration;
import net.openid.appauth.AuthState;
import net.openid.appauth.AuthorizationException;
import net.openid.appauth.AuthorizationResponse;
import net.openid.appauth.AuthorizationService;
import net.openid.appauth.AuthorizationServiceDiscovery;
import net.openid.appauth.ClientAuthentication;
import net.openid.appauth.ClientSecretBasic;
import net.openid.appauth.ClientSecretPost;
import net.openid.appauth.TokenRequest;
import okio.Okio;
import org.tanrabad.survey.BuildConfig;
import org.tanrabad.survey.R;
import org.tanrabad.survey.TanrabadApp;
import org.tanrabad.survey.presenter.LoginActivity;
import org.tanrabad.survey.presenter.TanrabadActivity;
import org.tanrabad.survey.presenter.authen.Authenticator;
import org.tanrabad.survey.presenter.authen.UserProfile;
public class TokenActivity extends TanrabadActivity {
private static final String TAG = "TokenActivity";
public static final String AUTH_ACTION_AUTO_LOGIN = "org.tanrabad.auth.action.AUTHEN";
public static final String USERNAME = "username";
public static final String AUTO_LOGIN = "auto_login";
private AuthorizationService mAuthService;
private AuthStateManager mStateManager;
private UserProfileManager mUserManager;
private UserStateManager mUserStateManager;
private final AtomicReference<UserProfile> mUserInfoJson = new AtomicReference<>();
private ExecutorService mExecutor;
private Button authenButton;
private View logoutButton;
private AppAuthPresenter auth;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_token);
mStateManager = AuthStateManager.getInstance(this);
mUserManager = UserProfileManager.getInstance(this);
mExecutor = Executors.newSingleThreadExecutor();
Configuration config = Configuration.getInstance(this);
mAuthService = new AuthorizationService(this,
new AppAuthConfiguration.Builder().setConnectionBuilder(config.getConnectionBuilder())
.build());
mUserInfoJson.compareAndSet(null, mUserManager.getProfile());
logoutButton = findViewById(R.id.logout);
logoutButton.setVisibility(View.GONE);
logoutButton.setOnClickListener(v -> logout());
authenButton = findViewById(R.id.authentication_button);
authenButton.setVisibility(View.GONE);
authenButton.setOnClickListener(v -> {
if (mUserStateManager != null && mUserStateManager.isRequireAction()) {
mUserInfoJson.set(null); //Clear for re-check user profile
checkAuthorize();
return;
}
UserProfile profile = mUserInfoJson.get();
Authenticator auth = new Authenticator(null);
auth.setAuthenWith(profile);
//Send back username to LoginActivity for fill-in app login process
Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra(USERNAME, profile.userName);
intent.putExtra(AUTO_LOGIN, AUTH_ACTION_AUTO_LOGIN.equals(getIntent().getAction()));
//Fellow line can't re-order
finish();
startActivity(intent);
});
checkAuthorize();
auth = new AppAuthPresenter(this);
}
@Override protected void onStop() {
super.onStop();
auth.close();
}
@Override protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
mUserInfoJson.set(null); //Clear for re-check user profile
checkAuthorize();
}
private void checkAuthorize() {
if (mExecutor.isShutdown()) {
mExecutor = Executors.newSingleThreadExecutor();
}
// the stored AuthState is incomplete, so check if we are currently receiving the result of
// the authorization flow from the browser.
AuthorizationResponse response = AuthorizationResponse.fromIntent(getIntent());
AuthorizationException ex = AuthorizationException.fromIntent(getIntent());
AuthState state = mStateManager.getCurrent();
if (state.isAuthorized() && response == null) {
Log.i(TAG, "Authorized state");
UserProfile profile = mUserInfoJson.get();
if (profile == null) {
Log.i(TAG, "Request User's profile with fresh token");
ClientAuthentication clientAuth =
new ClientSecretPost(BuildConfig.TRB_AUTHEN_CLIENT_SECRET);
state.performActionWithFreshTokens(mAuthService, clientAuth, this::fetchUserInfo);
} else {
Log.i(TAG, "Use stored User's Profile");
displayAuthorized();
}
return;
}
if (response != null || ex != null) {
mStateManager.updateAfterAuthorization(response, ex);
}
if (response != null && response.authorizationCode != null) {
// authorization code exchange is required
mStateManager.updateAfterAuthorization(response, ex);
exchangeAuthorizationCode(response);
} else if (ex != null) {
displayNotAuthorized("Authorization flow failed: " + ex.getMessage());
TanrabadApp.log(ex);
} else {
displayNotAuthorized("No authorization state retained - reauthorization required");
TanrabadApp.log(new IllegalStateException("No authorization state retained"));
logout();
}
}
@Override protected void onDestroy() {
super.onDestroy();
mAuthService.dispose();
mExecutor.shutdownNow();
}
@MainThread private void displayNotAuthorized(String explanation) {
((TextView) findViewById(R.id.username)).setText(R.string.please_authen);
Toast.makeText(this, explanation, Toast.LENGTH_SHORT).show();
restartToLoginActivity();
}
private void restartToLoginActivity() {
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
@MainThread private void displayAuthorized() {
Log.i(TAG, "Display Authorized");
authenButton.setVisibility(View.VISIBLE);
logoutButton.setVisibility(View.VISIBLE);
UserProfile userInfo = mUserInfoJson.get();
if (userInfo != null) {
((TextView) findViewById(R.id.username)).setText(userInfo.userName);
((TextView) findViewById(R.id.user_fullname)).setText(userInfo.name);
String orgName = userInfo.orgName;
if (!TextUtils.isEmpty(orgName)) {
((TextView) findViewById(R.id.organization)).setText(userInfo.orgName);
} else {
((TextView) findViewById(R.id.organization)).setText("ไม่ระบุหน่วยงาน");
}
mUserStateManager = new UserStateManager(userInfo);
TextView status = findViewById(R.id.status);
status.setText(mUserStateManager.getUserStateRes());
if (mUserStateManager.isRequireAction()) {
status.setTextColor(ContextCompat.getColor(this, R.color.black));
mUserStateManager.performRequireAction(this);
authenButton.setText(R.string.check_status);
} else {
status.setTextColor(ContextCompat.getColor(this, R.color.without_larvae));
authenButton.setText(R.string.login);
String action = getIntent().getAction();
if (AUTH_ACTION_AUTO_LOGIN.equals(action)) {
authenButton.performClick(); //automatic login to app
}
}
} else {
Toast.makeText(this, "เกิดข้อผิดพลาด ไม่สามารถดึงข้อมูลผู้ใช้ได้", Toast.LENGTH_SHORT)
.show();
restartToLoginActivity();
}
}
@MainThread
private void exchangeAuthorizationCode(AuthorizationResponse authorizationResponse) {
Log.i(TAG, "Request to Exchange token");
final TokenRequest request = authorizationResponse.createTokenExchangeRequest();
performTokenRequest(request, (tokenResponse, authException) -> {
mStateManager.updateAfterTokenResponse(tokenResponse, authException);
if (!mStateManager.getCurrent().isAuthorized()) {
final String message =
"Authorization Code exchange failed - " + ((authException != null)
? authException.error : "");
Log.e(TAG, message);
runOnUiThread(() -> displayNotAuthorized(message));
} else {
mStateManager.getCurrent()
.performActionWithFreshTokens(mAuthService, this::fetchUserInfo);
}
});
}
@MainThread private void performTokenRequest(TokenRequest request,
AuthorizationService.TokenResponseCallback callback) {
ClientAuthentication client = new ClientSecretBasic(BuildConfig.TRB_AUTHEN_CLIENT_SECRET);
mAuthService.performTokenRequest(request, client, callback);
}
@MainThread private void fetchUserInfo(final String accessToken, String idToken,
AuthorizationException ex) {
Log.d(TAG, String.format("fetchUserInfo with accessToken=%s idToken=%s", accessToken, idToken));
if (ex != null) {
Log.e(TAG, "Token refresh failed when fetching user info");
TanrabadApp.log(ex);
mUserInfoJson.set(null);
runOnUiThread(() -> displayNotAuthorized("ไม่สามารถแลกเปลี่ยนข้อมูลกับ Server ได้"));
return;
}
AuthorizationServiceDiscovery discovery =
mStateManager.getCurrent().getAuthorizationServiceConfiguration().discoveryDoc;
final URL userInfoEndpoint;
try {
Uri userinfoEndpoint = discovery.getUserinfoEndpoint();
Log.i(TAG, "Request user profile at " + userinfoEndpoint);
userInfoEndpoint = new URL(userinfoEndpoint.toString());
} catch (MalformedURLException urlEx) {
Log.e(TAG, "Failed to construct user info endpoint URL", urlEx);
TanrabadApp.log(urlEx);
mUserInfoJson.set(null);
runOnUiThread(() -> displayNotAuthorized("ไม่สามารถดึงข้อมูลผู้ใช้ได้"));
return;
}
mExecutor.submit(() -> {
try {
HttpURLConnection conn = (HttpURLConnection) userInfoEndpoint.openConnection();
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setInstanceFollowRedirects(false);
String response = Okio.buffer(Okio.source(conn.getInputStream()))
.readString(Charset.forName("UTF-8"));
mUserInfoJson.set(UserProfile.fromJson(response));
mUserManager.save(mUserInfoJson.get());
} catch (IOException ioEx) {
Log.e(TAG, "Network error when querying userinfo endpoint", ioEx);
TokenActivity.this.showSnackbar("Fetching user info failed");
}
runOnUiThread(this::displayAuthorized);
});
}
@MainThread private void showSnackbar(String message) {
Snackbar.make(findViewById(R.id.coordinator), message, Snackbar.LENGTH_SHORT).show();
}
@MainThread private void logout() {
// discard the authorization and token state, but retain the configuration and
// dynamic client registration (if applicable), to save from retrieving them again.
auth.logout();
finish();
}
}
| /*
* Copyright (c) 2018 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* 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 IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5;
import IMPORT_6.content.Intent;
import IMPORT_6.IMPORT_7.IMPORT_8;
import IMPORT_6.IMPORT_9.IMPORT_10;
import IMPORT_6.IMPORT_11.IMPORT_12.IMPORT_13;
import IMPORT_6.IMPORT_11.design.IMPORT_14.Snackbar;
import IMPORT_6.IMPORT_11.IMPORT_15.content.IMPORT_16;
import IMPORT_6.IMPORT_17.TextUtils;
import IMPORT_6.IMPORT_18.Log;
import IMPORT_6.IMPORT_19.IMPORT_20;
import IMPORT_6.IMPORT_14.Button;
import IMPORT_6.IMPORT_14.IMPORT_21;
import IMPORT_6.IMPORT_14.IMPORT_22;
import IMPORT_23.IMPORT_24.IMPORT_25;
import IMPORT_23.IMPORT_7.IMPORT_26;
import IMPORT_23.IMPORT_7.IMPORT_27;
import IMPORT_23.IMPORT_7.URL;
import IMPORT_23.IMPORT_28.IMPORT_29.IMPORT_30;
import IMPORT_23.IMPORT_18.IMPORT_31.IMPORT_32;
import IMPORT_23.IMPORT_18.IMPORT_31.Executors;
import IMPORT_23.IMPORT_18.IMPORT_31.IMPORT_33.AtomicReference;
import IMPORT_7.IMPORT_34.IMPORT_5.IMPORT_35;
import IMPORT_7.IMPORT_34.IMPORT_5.IMPORT_36;
import IMPORT_7.IMPORT_34.IMPORT_5.IMPORT_37;
import IMPORT_7.IMPORT_34.IMPORT_5.IMPORT_38;
import IMPORT_7.IMPORT_34.IMPORT_5.IMPORT_39;
import IMPORT_7.IMPORT_34.IMPORT_5.IMPORT_40;
import IMPORT_7.IMPORT_34.IMPORT_5.IMPORT_41;
import IMPORT_7.IMPORT_34.IMPORT_5.IMPORT_42;
import IMPORT_7.IMPORT_34.IMPORT_5.ClientSecretPost;
import IMPORT_7.IMPORT_34.IMPORT_5.IMPORT_43;
import IMPORT_44.Okio;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_45;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_46;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_47;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.LoginActivity;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_48;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_49;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.UserProfile;
public class CLASS_0 extends IMPORT_48 {
private static final CLASS_1 TAG = "TokenActivity";
public static final CLASS_1 VAR_2 = "org.tanrabad.auth.action.AUTHEN";
public static final CLASS_1 VAR_3 = "username";
public static final CLASS_1 VAR_4 = "auto_login";
private IMPORT_39 VAR_5;
private CLASS_2 VAR_7;
private CLASS_3 VAR_9;
private CLASS_4 VAR_10;
private final AtomicReference<UserProfile> VAR_11 = new AtomicReference<>();
private IMPORT_32 VAR_12;
private Button VAR_13;
private IMPORT_20 logoutButton;
private CLASS_5 VAR_14;
@Override protected void FUNC_0(IMPORT_10 savedInstanceState) {
super.FUNC_0(savedInstanceState);
FUNC_1(IMPORT_46.VAR_15.VAR_16);
VAR_7 = VAR_6.FUNC_2(this);
VAR_9 = VAR_8.FUNC_2(this);
VAR_12 = Executors.FUNC_3();
CLASS_6 VAR_18 = VAR_17.FUNC_2(this);
VAR_5 = new IMPORT_39(this,
new IMPORT_35.CLASS_7().FUNC_4(VAR_18.FUNC_5())
.FUNC_6());
VAR_11.FUNC_7(null, VAR_9.FUNC_8());
logoutButton = FUNC_9(IMPORT_46.VAR_19.VAR_20);
logoutButton.FUNC_11(IMPORT_20.VAR_21);
logoutButton.FUNC_12(VAR_22 -> FUNC_10());
VAR_13 = FUNC_9(IMPORT_46.VAR_19.VAR_23);
VAR_13.FUNC_11(IMPORT_20.VAR_21);
VAR_13.FUNC_12(VAR_22 -> {
if (VAR_10 != null && VAR_10.FUNC_13()) {
VAR_11.FUNC_14(null); //Clear for re-check user profile
FUNC_15();
return;
}
UserProfile VAR_24 = VAR_11.FUNC_16();
IMPORT_49 VAR_14 = new IMPORT_49(null);
VAR_14.FUNC_17(VAR_24);
//Send back username to LoginActivity for fill-in app login process
Intent VAR_25 = new Intent(this, LoginActivity.class);
VAR_25.FUNC_18(VAR_3, VAR_24.VAR_26);
VAR_25.FUNC_18(VAR_4, VAR_2.equals(FUNC_19().FUNC_20()));
//Fellow line can't re-order
FUNC_21();
FUNC_22(VAR_25);
});
FUNC_15();
VAR_14 = new CLASS_5(this);
}
@Override protected void FUNC_23() {
super.FUNC_23();
VAR_14.FUNC_24();
}
@Override protected void FUNC_25(Intent VAR_25) {
super.FUNC_25(VAR_25);
VAR_11.FUNC_14(null); //Clear for re-check user profile
FUNC_15();
}
private void FUNC_15() {
if (VAR_12.FUNC_26()) {
VAR_12 = Executors.FUNC_3();
}
// the stored AuthState is incomplete, so check if we are currently receiving the result of
// the authorization flow from the browser.
IMPORT_38 VAR_27 = IMPORT_38.FUNC_27(FUNC_19());
IMPORT_37 VAR_28 = IMPORT_37.FUNC_27(FUNC_19());
IMPORT_36 VAR_29 = VAR_7.FUNC_28();
if (VAR_29.FUNC_29() && VAR_27 == null) {
Log.FUNC_30(TAG, "Authorized state");
UserProfile VAR_24 = VAR_11.FUNC_16();
if (VAR_24 == null) {
Log.FUNC_30(TAG, "Request User's profile with fresh token");
IMPORT_41 VAR_30 =
new ClientSecretPost(IMPORT_45.VAR_31);
VAR_29.FUNC_31(VAR_5, VAR_30, this::VAR_32);
} else {
Log.FUNC_30(TAG, "Use stored User's Profile");
FUNC_33();
}
return;
}
if (VAR_27 != null || VAR_28 != null) {
VAR_7.FUNC_34(VAR_27, VAR_28);
}
if (VAR_27 != null && VAR_27.VAR_34 != null) {
// authorization code exchange is required
VAR_7.FUNC_34(VAR_27, VAR_28);
FUNC_35(VAR_27);
} else if (VAR_28 != null) {
FUNC_36("Authorization flow failed: " + VAR_28.getMessage());
IMPORT_47.FUNC_37(VAR_28);
} else {
FUNC_36("No authorization state retained - reauthorization required");
IMPORT_47.FUNC_37(new CLASS_8("No authorization state retained"));
FUNC_10();
}
}
@Override protected void FUNC_38() {
super.FUNC_38();
VAR_5.FUNC_39();
VAR_12.FUNC_40();
}
@IMPORT_13 private void FUNC_36(CLASS_1 VAR_35) {
((IMPORT_21) FUNC_9(IMPORT_46.VAR_19.VAR_36)).FUNC_41(IMPORT_46.VAR_37.please_authen);
IMPORT_22.makeText(this, VAR_35, IMPORT_22.VAR_38).show();
FUNC_42();
}
private void FUNC_42() {
Intent VAR_25 = new Intent(this, LoginActivity.class);
VAR_25.FUNC_43(Intent.VAR_39 | Intent.VAR_40);
FUNC_22(VAR_25);
FUNC_21();
}
@IMPORT_13 private void FUNC_33() {
Log.FUNC_30(TAG, "Display Authorized");
VAR_13.FUNC_11(IMPORT_20.VAR_41);
logoutButton.FUNC_11(IMPORT_20.VAR_41);
UserProfile VAR_42 = VAR_11.FUNC_16();
if (VAR_42 != null) {
((IMPORT_21) FUNC_9(IMPORT_46.VAR_19.VAR_36)).FUNC_41(VAR_42.VAR_26);
((IMPORT_21) FUNC_9(IMPORT_46.VAR_19.VAR_43)).FUNC_41(VAR_42.VAR_44);
CLASS_1 VAR_45 = VAR_42.VAR_45;
if (!TextUtils.isEmpty(VAR_45)) {
((IMPORT_21) FUNC_9(IMPORT_46.VAR_19.VAR_46)).FUNC_41(VAR_42.VAR_45);
} else {
((IMPORT_21) FUNC_9(IMPORT_46.VAR_19.VAR_46)).FUNC_41("ไม่ระบุหน่วยงาน");
}
VAR_10 = new CLASS_4(VAR_42);
IMPORT_21 VAR_47 = FUNC_9(IMPORT_46.VAR_19.VAR_47);
VAR_47.FUNC_41(VAR_10.getUserStateRes());
if (VAR_10.FUNC_13()) {
VAR_47.FUNC_44(IMPORT_16.FUNC_45(this, IMPORT_46.VAR_48.VAR_49));
VAR_10.FUNC_46(this);
VAR_13.FUNC_41(IMPORT_46.VAR_37.check_status);
} else {
VAR_47.FUNC_44(IMPORT_16.FUNC_45(this, IMPORT_46.VAR_48.VAR_50));
VAR_13.FUNC_41(IMPORT_46.VAR_37.VAR_51);
CLASS_1 action = FUNC_19().FUNC_20();
if (VAR_2.equals(action)) {
VAR_13.FUNC_47(); //automatic login to app
}
}
} else {
IMPORT_22.makeText(this, "เกิดข้อผิดพลาด ไม่สามารถดึงข้อมูลผู้ใช้ได้", Toast.LENGTH_SHORT)
.show();
FUNC_42();
}
}
@IMPORT_13
private void FUNC_35(IMPORT_38 VAR_52) {
Log.FUNC_30(TAG, "Request to Exchange token");
final IMPORT_43 VAR_53 = VAR_52.FUNC_48();
FUNC_49(VAR_53, (tokenResponse, VAR_54) -> {
VAR_7.FUNC_50(tokenResponse, VAR_54);
if (!VAR_7.FUNC_28().FUNC_29()) {
final CLASS_1 VAR_55 =
"Authorization Code exchange failed - " + ((VAR_54 != null)
? VAR_54.VAR_56 : "");
Log.FUNC_51(TAG, VAR_55);
FUNC_52(() -> FUNC_36(VAR_55));
} else {
VAR_7.FUNC_28()
.FUNC_31(VAR_5, this::VAR_32);
}
});
}
@IMPORT_13 private void FUNC_49(IMPORT_43 VAR_53,
IMPORT_39.CLASS_9 VAR_57) {
IMPORT_41 VAR_58 = new IMPORT_42(IMPORT_45.VAR_31);
VAR_5.FUNC_49(VAR_53, VAR_58, VAR_57);
}
@IMPORT_13 private void FUNC_32(final CLASS_1 VAR_59, CLASS_1 VAR_60,
IMPORT_37 VAR_28) {
Log.FUNC_53(TAG, VAR_1.FUNC_54("fetchUserInfo with accessToken=%s idToken=%s", VAR_59, VAR_60));
if (VAR_28 != null) {
Log.FUNC_51(TAG, "Token refresh failed when fetching user info");
IMPORT_47.FUNC_37(VAR_28);
VAR_11.FUNC_14(null);
FUNC_52(() -> FUNC_36("ไม่สามารถแลกเปลี่ยนข้อมูลกับ Server ได้"));
return;
}
IMPORT_40 VAR_61 =
VAR_7.FUNC_28().FUNC_55().VAR_62;
final URL VAR_63;
try {
IMPORT_8 VAR_64 = VAR_61.FUNC_56();
Log.FUNC_30(TAG, "Request user profile at " + VAR_64);
VAR_63 = new URL(VAR_64.FUNC_57());
} catch (IMPORT_27 urlEx) {
Log.FUNC_51(TAG, "Failed to construct user info endpoint URL", urlEx);
IMPORT_47.FUNC_37(urlEx);
VAR_11.FUNC_14(null);
FUNC_52(() -> FUNC_36("ไม่สามารถดึงข้อมูลผู้ใช้ได้"));
return;
}
VAR_12.FUNC_58(() -> {
try {
IMPORT_26 VAR_65 = (IMPORT_26) VAR_63.FUNC_59();
VAR_65.FUNC_60("Authorization", "Bearer " + VAR_59);
VAR_65.FUNC_61(false);
CLASS_1 VAR_27 = Okio.FUNC_62(Okio.FUNC_63(VAR_65.FUNC_64()))
.FUNC_65(IMPORT_30.FUNC_66("UTF-8"));
VAR_11.FUNC_14(UserProfile.FUNC_67(VAR_27));
VAR_9.FUNC_68(VAR_11.FUNC_16());
} catch (IMPORT_25 ioEx) {
Log.FUNC_51(TAG, "Network error when querying userinfo endpoint", ioEx);
VAR_0.this.showSnackbar("Fetching user info failed");
}
FUNC_52(this::VAR_33);
});
}
@IMPORT_13 private void showSnackbar(CLASS_1 VAR_55) {
Snackbar.FUNC_69(FUNC_9(IMPORT_46.VAR_19.VAR_66), VAR_55, Snackbar.VAR_38).show();
}
@IMPORT_13 private void FUNC_10() {
// discard the authorization and token state, but retain the configuration and
// dynamic client registration (if applicable), to save from retrieving them again.
VAR_14.FUNC_10();
FUNC_21();
}
}
| 0.830628 | {'IMPORT_0': 'org', 'IMPORT_1': 'tanrabad', 'IMPORT_2': 'survey', 'IMPORT_3': 'presenter', 'IMPORT_4': 'authen', 'IMPORT_5': 'appauth', 'IMPORT_6': 'android', 'IMPORT_7': 'net', 'IMPORT_8': 'Uri', 'IMPORT_9': 'os', 'IMPORT_10': 'Bundle', 'IMPORT_11': 'support', 'IMPORT_12': 'annotation', 'IMPORT_13': 'MainThread', 'IMPORT_14': 'widget', 'IMPORT_15': 'v4', 'IMPORT_16': 'ContextCompat', 'IMPORT_17': 'text', 'IMPORT_18': 'util', 'IMPORT_19': 'view', 'IMPORT_20': 'View', 'IMPORT_21': 'TextView', 'IMPORT_22': 'Toast', 'IMPORT_23': 'java', 'IMPORT_24': 'io', 'IMPORT_25': 'IOException', 'IMPORT_26': 'HttpURLConnection', 'IMPORT_27': 'MalformedURLException', 'IMPORT_28': 'nio', 'IMPORT_29': 'charset', 'IMPORT_30': 'Charset', 'IMPORT_31': 'concurrent', 'IMPORT_32': 'ExecutorService', 'IMPORT_33': 'atomic', 'IMPORT_34': 'openid', 'IMPORT_35': 'AppAuthConfiguration', 'IMPORT_36': 'AuthState', 'IMPORT_37': 'AuthorizationException', 'IMPORT_38': 'AuthorizationResponse', 'IMPORT_39': 'AuthorizationService', 'IMPORT_40': 'AuthorizationServiceDiscovery', 'IMPORT_41': 'ClientAuthentication', 'IMPORT_42': 'ClientSecretBasic', 'IMPORT_43': 'TokenRequest', 'IMPORT_44': 'okio', 'IMPORT_45': 'BuildConfig', 'IMPORT_46': 'R', 'IMPORT_47': 'TanrabadApp', 'IMPORT_48': 'TanrabadActivity', 'IMPORT_49': 'Authenticator', 'CLASS_0': 'TokenActivity', 'VAR_0': 'TokenActivity', 'CLASS_1': 'String', 'VAR_1': 'String', 'VAR_2': 'AUTH_ACTION_AUTO_LOGIN', 'VAR_3': 'USERNAME', 'VAR_4': 'AUTO_LOGIN', 'VAR_5': 'mAuthService', 'CLASS_2': 'AuthStateManager', 'VAR_6': 'AuthStateManager', 'VAR_7': 'mStateManager', 'CLASS_3': 'UserProfileManager', 'VAR_8': 'UserProfileManager', 'VAR_9': 'mUserManager', 'CLASS_4': 'UserStateManager', 'VAR_10': 'mUserStateManager', 'VAR_11': 'mUserInfoJson', 'VAR_12': 'mExecutor', 'VAR_13': 'authenButton', 'CLASS_5': 'AppAuthPresenter', 'VAR_14': 'auth', 'FUNC_0': 'onCreate', 'FUNC_1': 'setContentView', 'VAR_15': 'layout', 'VAR_16': 'activity_token', 'FUNC_2': 'getInstance', 'FUNC_3': 'newSingleThreadExecutor', 'CLASS_6': 'Configuration', 'VAR_17': 'Configuration', 'VAR_18': 'config', 'CLASS_7': 'Builder', 'FUNC_4': 'setConnectionBuilder', 'FUNC_5': 'getConnectionBuilder', 'FUNC_6': 'build', 'FUNC_7': 'compareAndSet', 'FUNC_8': 'getProfile', 'FUNC_9': 'findViewById', 'VAR_19': 'id', 'VAR_20': 'logout', 'FUNC_10': 'logout', 'FUNC_11': 'setVisibility', 'VAR_21': 'GONE', 'FUNC_12': 'setOnClickListener', 'VAR_22': 'v', 'VAR_23': 'authentication_button', 'FUNC_13': 'isRequireAction', 'FUNC_14': 'set', 'FUNC_15': 'checkAuthorize', 'VAR_24': 'profile', 'FUNC_16': 'get', 'FUNC_17': 'setAuthenWith', 'VAR_25': 'intent', 'FUNC_18': 'putExtra', 'VAR_26': 'userName', 'FUNC_19': 'getIntent', 'FUNC_20': 'getAction', 'FUNC_21': 'finish', 'FUNC_22': 'startActivity', 'FUNC_23': 'onStop', 'FUNC_24': 'close', 'FUNC_25': 'onNewIntent', 'FUNC_26': 'isShutdown', 'VAR_27': 'response', 'FUNC_27': 'fromIntent', 'VAR_28': 'ex', 'VAR_29': 'state', 'FUNC_28': 'getCurrent', 'FUNC_29': 'isAuthorized', 'FUNC_30': 'i', 'VAR_30': 'clientAuth', 'VAR_31': 'TRB_AUTHEN_CLIENT_SECRET', 'FUNC_31': 'performActionWithFreshTokens', 'VAR_32': 'fetchUserInfo', 'FUNC_32': 'fetchUserInfo', 'FUNC_33': 'displayAuthorized', 'VAR_33': 'displayAuthorized', 'FUNC_34': 'updateAfterAuthorization', 'VAR_34': 'authorizationCode', 'FUNC_35': 'exchangeAuthorizationCode', 'FUNC_36': 'displayNotAuthorized', 'FUNC_37': 'log', 'CLASS_8': 'IllegalStateException', 'FUNC_38': 'onDestroy', 'FUNC_39': 'dispose', 'FUNC_40': 'shutdownNow', 'VAR_35': 'explanation', 'VAR_36': 'username', 'FUNC_41': 'setText', 'VAR_37': 'string', 'VAR_38': 'LENGTH_SHORT', 'FUNC_42': 'restartToLoginActivity', 'FUNC_43': 'setFlags', 'VAR_39': 'FLAG_ACTIVITY_CLEAR_TOP', 'VAR_40': 'FLAG_ACTIVITY_CLEAR_TASK', 'VAR_41': 'VISIBLE', 'VAR_42': 'userInfo', 'VAR_43': 'user_fullname', 'VAR_44': 'name', 'VAR_45': 'orgName', 'VAR_46': 'organization', 'VAR_47': 'status', 'FUNC_44': 'setTextColor', 'FUNC_45': 'getColor', 'VAR_48': 'color', 'VAR_49': 'black', 'FUNC_46': 'performRequireAction', 'VAR_50': 'without_larvae', 'VAR_51': 'login', 'FUNC_47': 'performClick', 'VAR_52': 'authorizationResponse', 'VAR_53': 'request', 'FUNC_48': 'createTokenExchangeRequest', 'FUNC_49': 'performTokenRequest', 'VAR_54': 'authException', 'FUNC_50': 'updateAfterTokenResponse', 'VAR_55': 'message', 'VAR_56': 'error', 'FUNC_51': 'e', 'FUNC_52': 'runOnUiThread', 'CLASS_9': 'TokenResponseCallback', 'VAR_57': 'callback', 'VAR_58': 'client', 'VAR_59': 'accessToken', 'VAR_60': 'idToken', 'FUNC_53': 'd', 'FUNC_54': 'format', 'VAR_61': 'discovery', 'FUNC_55': 'getAuthorizationServiceConfiguration', 'VAR_62': 'discoveryDoc', 'VAR_63': 'userInfoEndpoint', 'VAR_64': 'userinfoEndpoint', 'FUNC_56': 'getUserinfoEndpoint', 'FUNC_57': 'toString', 'FUNC_58': 'submit', 'VAR_65': 'conn', 'FUNC_59': 'openConnection', 'FUNC_60': 'setRequestProperty', 'FUNC_61': 'setInstanceFollowRedirects', 'FUNC_62': 'buffer', 'FUNC_63': 'source', 'FUNC_64': 'getInputStream', 'FUNC_65': 'readString', 'FUNC_66': 'forName', 'FUNC_67': 'fromJson', 'FUNC_68': 'save', 'FUNC_69': 'make', 'VAR_66': 'coordinator'} | java | error | 0 |
/**
* HttpClient4 oauth2 http response.
*
* @author wautsns
* @since May 22, 2020
*/
@RequiredArgsConstructor
public class HttpClient4OAuth2HttpResponse implements OAuth2HttpResponse {
/** Original http response. */
private final HttpResponse origin;
@Override
public int getStatus() {
return origin.getStatusLine().getStatusCode();
}
@Override
public String getHeader(String name) {
return origin.getFirstHeader(name).getValue();
}
@Override
public List<String> getHeaders(String name) {
return Arrays.stream(origin.getHeaders(name))
.map(Header::getValue)
.collect(Collectors.toCollection(LinkedList::new));
}
@Override
public InputStream getInputStream() throws IOException {
return origin.getEntity().getContent();
}
@Override
public void close() throws OAuth2IOException {
if (origin instanceof Closeable) {
try {
((Closeable) origin).close();
} catch (IOException e) {
throw new OAuth2IOException(e);
}
}
}
} | /**
* HttpClient4 oauth2 http response.
*
* @author wautsns
* @since May 22, 2020
*/
@RequiredArgsConstructor
public class HttpClient4OAuth2HttpResponse implements OAuth2HttpResponse {
/** Original http response. */
private final CLASS_0 VAR_0;
@VAR_1
public int getStatus() {
return VAR_0.FUNC_0().FUNC_1();
}
@VAR_1
public String FUNC_2(String VAR_2) {
return VAR_0.getFirstHeader(VAR_2).FUNC_3();
}
@VAR_1
public List<String> FUNC_4(String VAR_2) {
return VAR_4.FUNC_5(VAR_0.FUNC_4(VAR_2))
.FUNC_6(Header::VAR_3)
.collect(Collectors.FUNC_7(VAR_5::new));
}
@VAR_1
public CLASS_1 FUNC_8() throws IOException {
return VAR_0.FUNC_9().FUNC_10();
}
@VAR_1
public void FUNC_11() throws CLASS_2 {
if (VAR_0 instanceof CLASS_3) {
try {
((CLASS_3) VAR_0).FUNC_11();
} catch (IOException VAR_6) {
throw new CLASS_2(VAR_6);
}
}
}
} | 0.769077 | {'CLASS_0': 'HttpResponse', 'VAR_0': 'origin', 'VAR_1': 'Override', 'FUNC_0': 'getStatusLine', 'FUNC_1': 'getStatusCode', 'FUNC_2': 'getHeader', 'VAR_2': 'name', 'FUNC_3': 'getValue', 'VAR_3': 'getValue', 'FUNC_4': 'getHeaders', 'VAR_4': 'Arrays', 'FUNC_5': 'stream', 'FUNC_6': 'map', 'FUNC_7': 'toCollection', 'VAR_5': 'LinkedList', 'CLASS_1': 'InputStream', 'FUNC_8': 'getInputStream', 'FUNC_9': 'getEntity', 'FUNC_10': 'getContent', 'FUNC_11': 'close', 'CLASS_2': 'OAuth2IOException', 'CLASS_3': 'Closeable', 'VAR_6': 'e'} | java | OOP | 48.05% |
/**
* Deletes a specific {@code Log} of a specified person.
*
* @throws CommandException if {@code Person} or {@code Log} is not found.
*/
public CommandResult deleteSpecificPersonLog(Model model) throws CommandException {
requireNonNull(model);
assert (this.isForOnePerson
&& !this.isForDeletingAllLogs
&& this.logIndex != null);
assert (!((this.personIndex == null && this.nameToDeleteLog == null)
|| (this.personIndex != null && this.nameToDeleteLog != null)));
Person personToEdit = this.getPersonToEdit(model);
Person deletedLogPerson = createdDeletedLogPerson(personToEdit, this.logIndex);
model.setPerson(personToEdit, deletedLogPerson);
model.updateFilteredPersonList(PREDICATE_SHOW_ALL_PERSONS);
return new CommandResult(MESSAGE_DELETE_LOG_SUCCESS);
} | /**
* Deletes a specific {@code Log} of a specified person.
*
* @throws CommandException if {@code Person} or {@code Log} is not found.
*/
public CLASS_0 deleteSpecificPersonLog(Model VAR_0) throws CLASS_1 {
FUNC_0(VAR_0);
assert (this.isForOnePerson
&& !this.isForDeletingAllLogs
&& this.logIndex != null);
assert (!((this.VAR_1 == null && this.VAR_2 == null)
|| (this.VAR_1 != null && this.VAR_2 != null)));
CLASS_2 VAR_3 = this.getPersonToEdit(VAR_0);
CLASS_2 VAR_4 = FUNC_1(VAR_3, this.logIndex);
VAR_0.FUNC_2(VAR_3, VAR_4);
VAR_0.FUNC_3(PREDICATE_SHOW_ALL_PERSONS);
return new CLASS_0(MESSAGE_DELETE_LOG_SUCCESS);
} | 0.550217 | {'CLASS_0': 'CommandResult', 'VAR_0': 'model', 'CLASS_1': 'CommandException', 'FUNC_0': 'requireNonNull', 'VAR_1': 'personIndex', 'VAR_2': 'nameToDeleteLog', 'CLASS_2': 'Person', 'VAR_3': 'personToEdit', 'VAR_4': 'deletedLogPerson', 'FUNC_1': 'createdDeletedLogPerson', 'FUNC_2': 'setPerson', 'FUNC_3': 'updateFilteredPersonList'} | java | Texto | 3.85% |
package spark;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
import spark.http.matching.Configuration;
import static spark.Spark.*;
public class issue911Test {
Configuration configuration;
//CS304 Issue link: https://github.com/perwendel/spark/issues/911
@Before
public void init(){
configuration = Configuration.getConfiguration();
}
//CS304 Issue link: https://github.com/perwendel/spark/issues/911
@Test
public void TestResponseDefaultContentType() throws Exception {
get("/hello", (request, response) -> {
Assert.assertEquals("text/html; charset=utf-8", response.type());
return "Hello World!";
});
}
//CS304 Issue link: https://github.com/perwendel/spark/issues/911
@Test
public void TestResponseTypeModifiedByBefore() throws Exception {
before("/hello", (request, response) -> response.type("application/json"));
get("/hello", (request, response) -> {
Assert.assertEquals("text/html; charset=utf-8", configuration.getDefaultContentType());
Assert.assertEquals("application/json", response.type());
return "Hello World!";
});
}
//CS304 Issue link: https://github.com/perwendel/spark/issues/911
@Test
public void TestSetDefaultContentType() throws Exception {
configuration.setDefaultContentType("text/html");
get("/hello", (request, response) -> {
Assert.assertEquals("text/html",configuration.getDefaultContentType());
Assert.assertEquals("text/html", response.type());
return "Hello World!";
});
}
}
| package VAR_0;
import IMPORT_1.IMPORT_2.Assert;
import IMPORT_1.IMPORT_2.Test;
import IMPORT_1.IMPORT_2.IMPORT_3;
import IMPORT_0.IMPORT_4.IMPORT_5.Configuration;
import static IMPORT_0.IMPORT_6.*;
public class issue911Test {
Configuration configuration;
//CS304 Issue link: https://github.com/perwendel/spark/issues/911
@IMPORT_3
public void init(){
configuration = Configuration.FUNC_0();
}
//CS304 Issue link: https://github.com/perwendel/spark/issues/911
@Test
public void FUNC_1() throws CLASS_0 {
FUNC_2("/hello", (request, VAR_1) -> {
Assert.FUNC_3("text/html; charset=utf-8", VAR_1.FUNC_4());
return "Hello World!";
});
}
//CS304 Issue link: https://github.com/perwendel/spark/issues/911
@Test
public void FUNC_5() throws CLASS_0 {
FUNC_6("/hello", (request, VAR_1) -> VAR_1.FUNC_4("application/json"));
FUNC_2("/hello", (request, VAR_1) -> {
Assert.FUNC_3("text/html; charset=utf-8", configuration.getDefaultContentType());
Assert.FUNC_3("application/json", VAR_1.FUNC_4());
return "Hello World!";
});
}
//CS304 Issue link: https://github.com/perwendel/spark/issues/911
@Test
public void FUNC_7() throws CLASS_0 {
configuration.FUNC_8("text/html");
FUNC_2("/hello", (request, VAR_1) -> {
Assert.FUNC_3("text/html",configuration.getDefaultContentType());
Assert.FUNC_3("text/html", VAR_1.FUNC_4());
return "Hello World!";
});
}
}
| 0.604237 | {'VAR_0': 'spark', 'IMPORT_0': 'spark', 'IMPORT_1': 'org', 'IMPORT_2': 'junit', 'IMPORT_3': 'Before', 'IMPORT_4': 'http', 'IMPORT_5': 'matching', 'IMPORT_6': 'Spark', 'FUNC_0': 'getConfiguration', 'FUNC_1': 'TestResponseDefaultContentType', 'CLASS_0': 'Exception', 'FUNC_2': 'get', 'VAR_1': 'response', 'FUNC_3': 'assertEquals', 'FUNC_4': 'type', 'FUNC_5': 'TestResponseTypeModifiedByBefore', 'FUNC_6': 'before', 'FUNC_7': 'TestSetDefaultContentType', 'FUNC_8': 'setDefaultContentType'} | java | OOP | 37.11% |
package net.minecraft.network.rcon;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.SERVER)
public interface IServer
{
int getIntProperty(String key, int defaultValue);
String getStringProperty(String key, String defaultValue);
void setProperty(String key, Object value);
void saveProperties();
String getSettingsFilename();
String getHostname();
int getPort();
String getMotd();
String getMinecraftVersion();
int getCurrentPlayerCount();
int getMaxPlayers();
String[] getOnlinePlayerNames();
String getFolderName();
String getPlugins();
String handleRConCommand(String command);
boolean isDebuggingEnabled();
void logInfo(String msg);
void logWarning(String msg);
void logSevere(String msg);
void logDebug(String msg);
} | package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3;
import IMPORT_0.IMPORT_4.IMPORT_5.IMPORT_6.IMPORT_7;
import IMPORT_0.IMPORT_4.IMPORT_5.IMPORT_6.IMPORT_8;
@IMPORT_8(IMPORT_7.VAR_0)
public interface CLASS_0
{
int FUNC_0(CLASS_1 VAR_1, int VAR_2);
CLASS_1 FUNC_1(CLASS_1 VAR_1, CLASS_1 VAR_2);
void FUNC_2(CLASS_1 VAR_1, CLASS_2 VAR_3);
void FUNC_3();
CLASS_1 FUNC_4();
CLASS_1 FUNC_5();
int FUNC_6();
CLASS_1 FUNC_7();
CLASS_1 FUNC_8();
int FUNC_9();
int FUNC_10();
CLASS_1[] FUNC_11();
CLASS_1 FUNC_12();
CLASS_1 FUNC_13();
CLASS_1 FUNC_14(CLASS_1 VAR_4);
boolean FUNC_15();
void FUNC_16(CLASS_1 VAR_5);
void FUNC_17(CLASS_1 VAR_5);
void FUNC_18(CLASS_1 VAR_5);
void FUNC_19(CLASS_1 VAR_5);
} | 0.880171 | {'IMPORT_0': 'net', 'IMPORT_1': 'minecraft', 'IMPORT_2': 'network', 'IMPORT_3': 'rcon', 'IMPORT_4': 'minecraftforge', 'IMPORT_5': 'fml', 'IMPORT_6': 'relauncher', 'IMPORT_7': 'Side', 'IMPORT_8': 'SideOnly', 'VAR_0': 'SERVER', 'CLASS_0': 'IServer', 'FUNC_0': 'getIntProperty', 'CLASS_1': 'String', 'VAR_1': 'key', 'VAR_2': 'defaultValue', 'FUNC_1': 'getStringProperty', 'FUNC_2': 'setProperty', 'CLASS_2': 'Object', 'VAR_3': 'value', 'FUNC_3': 'saveProperties', 'FUNC_4': 'getSettingsFilename', 'FUNC_5': 'getHostname', 'FUNC_6': 'getPort', 'FUNC_7': 'getMotd', 'FUNC_8': 'getMinecraftVersion', 'FUNC_9': 'getCurrentPlayerCount', 'FUNC_10': 'getMaxPlayers', 'FUNC_11': 'getOnlinePlayerNames', 'FUNC_12': 'getFolderName', 'FUNC_13': 'getPlugins', 'FUNC_14': 'handleRConCommand', 'VAR_4': 'command', 'FUNC_15': 'isDebuggingEnabled', 'FUNC_16': 'logInfo', 'VAR_5': 'msg', 'FUNC_17': 'logWarning', 'FUNC_18': 'logSevere', 'FUNC_19': 'logDebug'} | java | Procedural | 20.16% |
/*
CloudGenix Controller SDK
(c) 2017 CloudGenix, Inc.
All Rights Reserved
https://www.cloudgenix.com
This SDK is released under the MIT license.
For support, please contact us on:
NetworkToCode Slack channel #cloudgenix: http://slack.networktocode.com
Email: <EMAIL>
*/
package CloudGenix;
import java.util.HashMap;
public class RestResponse {
public HashMap<String, String> headers;
public String contentType;
public long contentLength;
public int statusCode;
public String responseBody;
} | /*
CloudGenix Controller SDK
(c) 2017 CloudGenix, Inc.
All Rights Reserved
https://www.cloudgenix.com
This SDK is released under the MIT license.
For support, please contact us on:
NetworkToCode Slack channel #cloudgenix: http://slack.networktocode.com
Email: <EMAIL>
*/
package CloudGenix;
import java.util.HashMap;
public class CLASS_0 {
public HashMap<String, String> headers;
public String contentType;
public long contentLength;
public int VAR_0;
public String responseBody;
} | 0.157464 | {'CLASS_0': 'RestResponse', 'VAR_0': 'statusCode'} | java | Hibrido | 100.00% |
package sw.es.model.local;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import sw.es.domain.units.CompassRoseMetrics;
import sw.es.domain.units.DistanceMetrics;
import sw.es.domain.units.TemperatureMetrics;
/**
* Created by albertopenasamor on 3/11/15.
*/
public class ForecastWeather {
private String description;
private String icon;
private int iconId;
private double cloudiness;
private long datetime;
private double temp;
private double tempMin;
private double tempMax;
private double pressure;
private double humidity;
private double windSpeed;
private double windDegree;
public String getDescription() {
return description!=null?description:"";
}
public String getIcon() {
return icon!=null?icon:"";
}
public int getIconId() {
return iconId;
}
public double getCloudiness() {
return cloudiness;
}
public String getCloudinessPercent() {
return String.format("%.0f%s", cloudiness, "%");
}
public long getDatetime() {
return datetime;
}
public double getTemp() {
return temp;
}
public String getTempInCelsiusC() {
return String.format("%.0f", TemperatureMetrics.tempInCelsius(temp));
}
public double getTempMin() {
return tempMin;
}
public String getTempMinInCelsius() {
return String.format("%.0f", TemperatureMetrics.tempInCelsius(tempMin));
}
public double getTempMax() {
return tempMax;
}
public String getTempmaxInCelsius() {
return String.format("%.0f", TemperatureMetrics.tempInCelsius(tempMax));
}
public double getPressure() {
return pressure;
}
public double getHumidity() {
return humidity;
}
public String getHumidityPercent() {
return String.format("%.0f%s", humidity, "%");
}
public String getWindSpeedInKM() {
return String.format("%.0fKm/h", DistanceMetrics.kmPerHour(windSpeed));
}
public double getWindDegree() {
return windDegree;
}
public String getWindDegrees() {
return String.format("%s", CompassRoseMetrics.direction(windDegree));
}
public void setDescription(String description) {
this.description = description;
}
public void setIcon(String icon) {
this.icon = icon;
}
public void setIconId(int iconId) {
this.iconId = iconId;
}
public void setCloudiness(double cloudiness) {
this.cloudiness = cloudiness;
}
public void setDatetime(long datetime) {
this.datetime = datetime;
}
public void setTemp(double temp) {
this.temp = temp;
}
public void setTempMin(double tempMin) {
this.tempMin = tempMin;
}
public void setTempMax(double tempMax) {
this.tempMax = tempMax;
}
public void setPressure(double pressure) {
this.pressure = pressure;
}
public void setHumidity(double humidity) {
this.humidity = humidity;
}
public void setWindSpeed(double windSpeed) {
this.windSpeed = windSpeed;
}
public void setWindDegree(double windDegree) {
this.windDegree = windDegree;
}
public String getDatetimeFormatted() {
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm, EEE");
String outDate = formatter.print(datetime*1000L);
return outDate;
}
}
| package IMPORT_0.IMPORT_1.model.local;
import org.joda.time.format.IMPORT_2;
import org.joda.time.format.DateTimeFormatter;
import IMPORT_0.IMPORT_1.domain.units.CompassRoseMetrics;
import IMPORT_0.IMPORT_1.domain.units.DistanceMetrics;
import IMPORT_0.IMPORT_1.domain.units.TemperatureMetrics;
/**
* Created by albertopenasamor on 3/11/15.
*/
public class CLASS_0 {
private String description;
private String VAR_0;
private int VAR_1;
private double cloudiness;
private long datetime;
private double temp;
private double VAR_2;
private double tempMax;
private double pressure;
private double humidity;
private double windSpeed;
private double windDegree;
public String getDescription() {
return description!=null?description:"";
}
public String getIcon() {
return VAR_0!=null?VAR_0:"";
}
public int getIconId() {
return VAR_1;
}
public double getCloudiness() {
return cloudiness;
}
public String getCloudinessPercent() {
return String.format("%.0f%s", cloudiness, "%");
}
public long getDatetime() {
return datetime;
}
public double getTemp() {
return temp;
}
public String getTempInCelsiusC() {
return String.format("%.0f", TemperatureMetrics.tempInCelsius(temp));
}
public double getTempMin() {
return VAR_2;
}
public String getTempMinInCelsius() {
return String.format("%.0f", TemperatureMetrics.tempInCelsius(VAR_2));
}
public double getTempMax() {
return tempMax;
}
public String getTempmaxInCelsius() {
return String.format("%.0f", TemperatureMetrics.tempInCelsius(tempMax));
}
public double getPressure() {
return pressure;
}
public double getHumidity() {
return humidity;
}
public String getHumidityPercent() {
return String.format("%.0f%s", humidity, "%");
}
public String getWindSpeedInKM() {
return String.format("%.0fKm/h", DistanceMetrics.kmPerHour(windSpeed));
}
public double getWindDegree() {
return windDegree;
}
public String getWindDegrees() {
return String.format("%s", CompassRoseMetrics.FUNC_0(windDegree));
}
public void FUNC_1(String description) {
this.description = description;
}
public void setIcon(String VAR_0) {
this.VAR_0 = VAR_0;
}
public void setIconId(int VAR_1) {
this.VAR_1 = VAR_1;
}
public void setCloudiness(double cloudiness) {
this.cloudiness = cloudiness;
}
public void setDatetime(long datetime) {
this.datetime = datetime;
}
public void setTemp(double temp) {
this.temp = temp;
}
public void setTempMin(double VAR_2) {
this.VAR_2 = VAR_2;
}
public void FUNC_2(double tempMax) {
this.tempMax = tempMax;
}
public void setPressure(double pressure) {
this.pressure = pressure;
}
public void FUNC_3(double humidity) {
this.humidity = humidity;
}
public void setWindSpeed(double windSpeed) {
this.windSpeed = windSpeed;
}
public void setWindDegree(double windDegree) {
this.windDegree = windDegree;
}
public String getDatetimeFormatted() {
DateTimeFormatter VAR_3 = IMPORT_2.forPattern("HH:mm, EEE");
String outDate = VAR_3.print(datetime*1000L);
return outDate;
}
}
| 0.224801 | {'IMPORT_0': 'sw', 'IMPORT_1': 'es', 'IMPORT_2': 'DateTimeFormat', 'CLASS_0': 'ForecastWeather', 'VAR_0': 'icon', 'VAR_1': 'iconId', 'VAR_2': 'tempMin', 'FUNC_0': 'direction', 'FUNC_1': 'setDescription', 'FUNC_2': 'setTempMax', 'FUNC_3': 'setHumidity', 'VAR_3': 'formatter'} | java | OOP | 35.36% |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.engine;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.lucene.search.Queries;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.io.IOException;
public final class EngineSearcherTotalHitsMatcher extends TypeSafeMatcher<Engine.Searcher> {
private final Query query;
private final int totalHits;
private int count;
public EngineSearcherTotalHitsMatcher(Query query, int totalHits) {
this.query = query;
this.totalHits = totalHits;
}
@Override
public boolean matchesSafely(Engine.Searcher searcher) {
try {
this.count = searcher.count(query);
return count == totalHits;
} catch (IOException e) {
return false;
}
}
@Override
protected void describeMismatchSafely(Engine.Searcher item, Description mismatchDescription) {
mismatchDescription.appendText("was ").appendValue(count);
}
@Override
public void describeTo(Description description) {
description.appendText("total hits of size ").appendValue(totalHits).appendText(" with query ").appendValue(query);
}
public static Matcher<Engine.Searcher> engineSearcherTotalHits(Query query, int totalHits) {
return new EngineSearcherTotalHitsMatcher(query, totalHits);
}
public static Matcher<Engine.Searcher> engineSearcherTotalHits(int totalHits) {
return new EngineSearcherTotalHitsMatcher(Queries.newMatchAllQuery(), totalHits);
}
}
| /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package IMPORT_0.IMPORT_1.index.IMPORT_2;
import IMPORT_0.IMPORT_3.IMPORT_4.IMPORT_5.IMPORT_6;
import IMPORT_0.IMPORT_1.common.IMPORT_4.IMPORT_5.IMPORT_7;
import IMPORT_0.hamcrest.IMPORT_8;
import IMPORT_0.hamcrest.IMPORT_9;
import IMPORT_0.hamcrest.IMPORT_10;
import java.IMPORT_11.IOException;
public final class CLASS_0 extends IMPORT_10<Engine.CLASS_1> {
private final IMPORT_6 VAR_0;
private final int VAR_1;
private int VAR_2;
public CLASS_0(IMPORT_6 VAR_0, int VAR_1) {
this.VAR_0 = VAR_0;
this.VAR_1 = VAR_1;
}
@VAR_3
public boolean FUNC_1(Engine.CLASS_1 VAR_4) {
try {
this.VAR_2 = VAR_4.FUNC_0(VAR_0);
return VAR_2 == VAR_1;
} catch (IOException VAR_5) {
return false;
}
}
@VAR_3
protected void FUNC_2(Engine.CLASS_1 VAR_6, IMPORT_8 VAR_7) {
VAR_7.FUNC_3("was ").appendValue(VAR_2);
}
@VAR_3
public void FUNC_4(IMPORT_8 VAR_8) {
VAR_8.FUNC_3("total hits of size ").appendValue(VAR_1).FUNC_3(" with query ").appendValue(VAR_0);
}
public static IMPORT_9<Engine.CLASS_1> FUNC_5(IMPORT_6 VAR_0, int VAR_1) {
return new CLASS_0(VAR_0, VAR_1);
}
public static IMPORT_9<Engine.CLASS_1> FUNC_5(int VAR_1) {
return new CLASS_0(IMPORT_7.FUNC_6(), VAR_1);
}
}
| 0.873482 | {'IMPORT_0': 'org', 'IMPORT_1': 'elasticsearch', 'IMPORT_2': 'engine', 'IMPORT_3': 'apache', 'IMPORT_4': 'lucene', 'IMPORT_5': 'search', 'IMPORT_6': 'Query', 'IMPORT_7': 'Queries', 'IMPORT_8': 'Description', 'IMPORT_9': 'Matcher', 'IMPORT_10': 'TypeSafeMatcher', 'IMPORT_11': 'io', 'CLASS_0': 'EngineSearcherTotalHitsMatcher', 'CLASS_1': 'Searcher', 'VAR_0': 'query', 'VAR_1': 'totalHits', 'VAR_2': 'count', 'FUNC_0': 'count', 'VAR_3': 'Override', 'FUNC_1': 'matchesSafely', 'VAR_4': 'searcher', 'VAR_5': 'e', 'FUNC_2': 'describeMismatchSafely', 'VAR_6': 'item', 'VAR_7': 'mismatchDescription', 'FUNC_3': 'appendText', 'FUNC_4': 'describeTo', 'VAR_8': 'description', 'FUNC_5': 'engineSearcherTotalHits', 'FUNC_6': 'newMatchAllQuery'} | java | OOP | 97.97% |
/*
* This method is called when a player has either joined or left the network. This method is called
* from the Update Message object and this Message originates from the Registry. "topic" is either
* "join" or "leave" and "userName" is the user name of the player either joining or leaving the
* network. This method is required to implement the Subscriber interface. (described in
* Subscriber.java)
*/
@Override
public void update(String topic, String userName)
{
gui.addMessage("Server says: " + userName + " has " + (topic.equals("join") ? "joined" : "left"));
updatePlayers();
} | /*
* This method is called when a player has either joined or left the network. This method is called
* from the Update Message object and this Message originates from the Registry. "topic" is either
* "join" or "leave" and "userName" is the user name of the player either joining or leaving the
* network. This method is required to implement the Subscriber interface. (described in
* Subscriber.java)
*/
@Override
public void update(String VAR_0, String userName)
{
gui.addMessage("Server says: " + userName + " has " + (VAR_0.FUNC_0("join") ? "joined" : "left"));
updatePlayers();
} | 0.396483 | {'VAR_0': 'topic', 'FUNC_0': 'equals'} | java | Procedural | 88.64% |
/**
* Shows how to use the Android SDK to make a web API call.
*
* @author Adam Stroud <<a href="mailto:[email protected]">[email protected]</a>>
*/
public class NetworkCallAsyncTask
extends AsyncTask<String, Void, List<Manufacturer>> {
@Override
protected List<Manufacturer> doInBackground(String... params) {
HttpURLConnection connection = null;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
List<Manufacturer> manufacturers = new ArrayList<>();
try {
connection =
(HttpURLConnection) new URL(params[0])
.openConnection();
InputStream input =
new BufferedInputStream(connection.getInputStream());
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (!isCancelled()) {
JSONObject response = new JSONObject(buffer.toString());
JSONArray jsonManufacturers =
response.getJSONArray("manufacturers");
for (int i = 0; i < jsonManufacturers.length(); i++) {
JSONObject jsonManufacturer =
jsonManufacturers.getJSONObject(i);
Manufacturer manufacturer = new Manufacturer();
manufacturer
.setShortName(jsonManufacturer
.getString("short_name"));
manufacturer
.setLongName(jsonManufacturer
.getString("long_name"));
JSONArray jsonDevices =
jsonManufacturer.getJSONArray("devices");
List<Device> devices = new ArrayList<>();
for (int j = 0; j < jsonDevices.length(); j++) {
JSONObject jsonDevice =
jsonDevices.getJSONObject(j);
Device device = new Device();
device.setDisplaySizeInches((float) jsonDevice
.getDouble("display_size_inches"));
device.setNickname(jsonDevice
.getString("nickname"));
device.setModel(jsonDevice.getString("model"));
devices.add(device);
}
manufacturer.setDevices(devices);
manufacturers.add(manufacturer);
}
}
} catch (IOException | JSONException e) {
// Log error
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// do something meaningless
}
}
}
return manufacturers;
}
@Override
protected void onPostExecute(List<Manufacturer> manufacturers) {
super.onPostExecute(manufacturers);
if (!isCancelled()) {
// update display
}
}
} | /**
* Shows how to use the Android SDK to make a web API call.
*
* @author Adam Stroud <<a href="mailto:[email protected]">[email protected]</a>>
*/
public class CLASS_0
extends CLASS_1<String, CLASS_2, List<Manufacturer>> {
@Override
protected List<Manufacturer> doInBackground(String... params) {
CLASS_3 VAR_0 = null;
CLASS_4 buffer = new CLASS_4();
BufferedReader reader = null;
List<Manufacturer> manufacturers = new ArrayList<>();
try {
VAR_0 =
(CLASS_3) new CLASS_5(params[0])
.openConnection();
InputStream input =
new BufferedInputStream(VAR_0.getInputStream());
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (!isCancelled()) {
JSONObject response = new JSONObject(buffer.toString());
JSONArray jsonManufacturers =
response.getJSONArray("manufacturers");
for (int VAR_1 = 0; VAR_1 < jsonManufacturers.length(); VAR_1++) {
JSONObject jsonManufacturer =
jsonManufacturers.getJSONObject(VAR_1);
Manufacturer manufacturer = new Manufacturer();
manufacturer
.setShortName(jsonManufacturer
.getString("short_name"));
manufacturer
.setLongName(jsonManufacturer
.getString("long_name"));
JSONArray jsonDevices =
jsonManufacturer.getJSONArray("devices");
List<Device> devices = new ArrayList<>();
for (int j = 0; j < jsonDevices.length(); j++) {
JSONObject jsonDevice =
jsonDevices.getJSONObject(j);
Device device = new Device();
device.setDisplaySizeInches((float) jsonDevice
.getDouble("display_size_inches"));
device.setNickname(jsonDevice
.getString("nickname"));
device.setModel(jsonDevice.getString("model"));
devices.FUNC_0(device);
}
manufacturer.setDevices(devices);
manufacturers.FUNC_0(manufacturer);
}
}
} catch (IOException | JSONException e) {
// Log error
} finally {
if (VAR_0 != null) {
VAR_0.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// do something meaningless
}
}
}
return manufacturers;
}
@Override
protected void onPostExecute(List<Manufacturer> manufacturers) {
super.onPostExecute(manufacturers);
if (!isCancelled()) {
// update display
}
}
} | 0.095744 | {'CLASS_0': 'NetworkCallAsyncTask', 'CLASS_1': 'AsyncTask', 'CLASS_2': 'Void', 'CLASS_3': 'HttpURLConnection', 'VAR_0': 'connection', 'CLASS_4': 'StringBuffer', 'CLASS_5': 'URL', 'VAR_1': 'i', 'FUNC_0': 'add'} | java | OOP | 24.56% |
/**
* A "for" statement.
*/
class ForStatement extends StatementBase {
/**
* The init block.
*/
Statement init;
/**
* The condition.
*/
Expr condition;
/**
* The main loop block.
*/
Statement block;
/**
* The update list.
*/
ArrayList<Expr> updates = new ArrayList<>();
/**
* The type of the iterable.
*/
Type iterableType;
/**
* The iterable variable name.
*/
String iterableVariable;
/**
* The iterable expression.
*/
Expr iterable;
@Override
public void setMethod(MethodObj method) {
block.setMethod(method);
}
@Override
public String asString() {
StringBuilder buff = new StringBuilder();
buff.append("for (");
if (iterableType != null) {
Type it = iterable.getType();
if (it != null && it.arrayLevel > 0) {
String idx = "i_" + iterableVariable;
buff.append("int " + idx + " = 0; " +
idx + " < " + iterable.asString() + "->length(); " +
idx + "++");
buff.append(") {\n");
buff.append(JavaParser.indent(iterableType +
" " + iterableVariable + " = " +
iterable.asString() + "->at("+ idx +");\n"));
buff.append(block.toString()).append("}");
} else {
// TODO iterate over a collection
buff.append(iterableType).append(' ');
buff.append(iterableVariable).append(": ");
buff.append(iterable);
buff.append(") {\n");
buff.append(block.toString()).append("}");
}
} else {
buff.append(init.asString());
buff.append(" ").append(condition.asString()).append("; ");
for (int i = 0; i < updates.size(); i++) {
if (i > 0) {
buff.append(", ");
}
buff.append(updates.get(i).asString());
}
buff.append(") {\n");
buff.append(block.asString()).append("}");
}
return buff.toString();
}
} | /**
* A "for" statement.
*/
class ForStatement extends CLASS_0 {
/**
* The init block.
*/
Statement init;
/**
* The condition.
*/
CLASS_1 condition;
/**
* The main loop block.
*/
Statement block;
/**
* The update list.
*/
CLASS_2<CLASS_1> updates = new CLASS_2<>();
/**
* The type of the iterable.
*/
Type VAR_0;
/**
* The iterable variable name.
*/
CLASS_3 iterableVariable;
/**
* The iterable expression.
*/
CLASS_1 VAR_1;
@VAR_2
public void FUNC_0(MethodObj VAR_3) {
block.FUNC_0(VAR_3);
}
@VAR_2
public CLASS_3 asString() {
CLASS_4 VAR_4 = new CLASS_4();
VAR_4.append("for (");
if (VAR_0 != null) {
Type it = VAR_1.FUNC_1();
if (it != null && it.arrayLevel > 0) {
CLASS_3 idx = "i_" + iterableVariable;
VAR_4.append("int " + idx + " = 0; " +
idx + " < " + VAR_1.asString() + "->length(); " +
idx + "++");
VAR_4.append(") {\n");
VAR_4.append(VAR_5.indent(VAR_0 +
" " + iterableVariable + " = " +
VAR_1.asString() + "->at("+ idx +");\n"));
VAR_4.append(block.toString()).append("}");
} else {
// TODO iterate over a collection
VAR_4.append(VAR_0).append(' ');
VAR_4.append(iterableVariable).append(": ");
VAR_4.append(VAR_1);
VAR_4.append(") {\n");
VAR_4.append(block.toString()).append("}");
}
} else {
VAR_4.append(init.asString());
VAR_4.append(" ").append(condition.asString()).append("; ");
for (int i = 0; i < updates.FUNC_2(); i++) {
if (i > 0) {
VAR_4.append(", ");
}
VAR_4.append(updates.get(i).asString());
}
VAR_4.append(") {\n");
VAR_4.append(block.asString()).append("}");
}
return VAR_4.toString();
}
} | 0.590271 | {'CLASS_0': 'StatementBase', 'CLASS_1': 'Expr', 'CLASS_2': 'ArrayList', 'VAR_0': 'iterableType', 'CLASS_3': 'String', 'VAR_1': 'iterable', 'VAR_2': 'Override', 'FUNC_0': 'setMethod', 'VAR_3': 'method', 'CLASS_4': 'StringBuilder', 'VAR_4': 'buff', 'FUNC_1': 'getType', 'VAR_5': 'JavaParser', 'FUNC_2': 'size'} | java | OOP | 41.24% |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.widget;
import android.animation.Animator;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
/**
* Convenience class for listening for Animator events that implements the AnimatorListener
* interface and allows extending only methods that are necessary.
*
* @hide Hidden until this goes through review
*/
@RequiresApi(Build.VERSION_CODES.KITKAT_WATCH)
@RestrictTo(Scope.LIBRARY)
public class SimpleAnimatorListener implements Animator.AnimatorListener {
private boolean mWasCanceled;
@Override
public void onAnimationCancel(Animator animator) {
mWasCanceled = true;
}
@Override
public void onAnimationEnd(Animator animator) {
if (!mWasCanceled) {
onAnimationComplete(animator);
}
}
@Override
public void onAnimationRepeat(Animator animator) {}
@Override
public void onAnimationStart(Animator animator) {
mWasCanceled = false;
}
/**
* Called when the animation finishes. Not called if the animation was canceled.
*/
public void onAnimationComplete(Animator animator) {}
/**
* Provides information if the animation was cancelled.
*
* @return True if animation was cancelled.
*/
public boolean wasCanceled() {
return mWasCanceled;
}
}
| /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package IMPORT_0.IMPORT_1.IMPORT_2;
import IMPORT_3.IMPORT_4.IMPORT_5;
import IMPORT_3.IMPORT_6.IMPORT_7;
import IMPORT_0.IMPORT_8.IMPORT_9;
import IMPORT_0.IMPORT_8.IMPORT_10;
import IMPORT_0.IMPORT_8.IMPORT_10.IMPORT_11;
/**
* Convenience class for listening for Animator events that implements the AnimatorListener
* interface and allows extending only methods that are necessary.
*
* @hide Hidden until this goes through review
*/
@IMPORT_9(IMPORT_7.VAR_0.VAR_1)
@IMPORT_10(IMPORT_11.VAR_2)
public class CLASS_0 implements IMPORT_5.CLASS_1 {
private boolean VAR_3;
@VAR_4
public void FUNC_0(IMPORT_5 VAR_5) {
VAR_3 = true;
}
@VAR_4
public void FUNC_1(IMPORT_5 VAR_5) {
if (!VAR_3) {
onAnimationComplete(VAR_5);
}
}
@VAR_4
public void FUNC_2(IMPORT_5 VAR_5) {}
@VAR_4
public void FUNC_3(IMPORT_5 VAR_5) {
VAR_3 = false;
}
/**
* Called when the animation finishes. Not called if the animation was canceled.
*/
public void onAnimationComplete(IMPORT_5 VAR_5) {}
/**
* Provides information if the animation was cancelled.
*
* @return True if animation was cancelled.
*/
public boolean FUNC_4() {
return VAR_3;
}
}
| 0.980958 | {'IMPORT_0': 'androidx', 'IMPORT_1': 'wear', 'IMPORT_2': 'widget', 'IMPORT_3': 'android', 'IMPORT_4': 'animation', 'IMPORT_5': 'Animator', 'IMPORT_6': 'os', 'IMPORT_7': 'Build', 'IMPORT_8': 'annotation', 'IMPORT_9': 'RequiresApi', 'IMPORT_10': 'RestrictTo', 'IMPORT_11': 'Scope', 'VAR_0': 'VERSION_CODES', 'VAR_1': 'KITKAT_WATCH', 'VAR_2': 'LIBRARY', 'CLASS_0': 'SimpleAnimatorListener', 'CLASS_1': 'AnimatorListener', 'VAR_3': 'mWasCanceled', 'VAR_4': 'Override', 'FUNC_0': 'onAnimationCancel', 'VAR_5': 'animator', 'FUNC_1': 'onAnimationEnd', 'FUNC_2': 'onAnimationRepeat', 'FUNC_3': 'onAnimationStart', 'FUNC_4': 'wasCanceled'} | java | Hibrido | 100.00% |
package test.org.rockm.blink.httpserver;
import org.junit.Before;
import org.junit.Test;
import org.rockm.blink.httpserver.HttpExchangeBlinkResponse;
import java.io.IOException;
import java.util.Arrays;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import static org.rockm.blink.httpserver.HttpExchangeBlinkResponse.CONTENT_TYPE;
public class HttpExchangeBlinkResponseTest extends AbstractHttpExchangeBlinkResponseTest {
private static final String DEFAULT_CONTENT_TYPE = "app/json";
@Before
public void setUp() throws Exception {
super.setUp();
blinkResponse = new HttpExchangeBlinkResponse(DEFAULT_CONTENT_TYPE);
}
@Test
public void bodyShouldNotBeNull() throws Exception {
apply();
assertThat(responseOutputStream.toString("UTF-8"), is(""));
}
@Test
public void shouldHandleNullBody() throws Exception {
((HttpExchangeBlinkResponse)blinkResponse).setBody(null);
apply();
assertThat(responseOutputStream.toString("UTF-8"), is(""));
}
@Test
public void shouldSetStatusCode() throws Exception {
blinkResponse.status(404);
apply();
verify(httpExchange).sendResponseHeaders(404, 0);
}
@Test
public void defaultStatusShouldBe200() throws Exception {
apply();
verify(httpExchange).sendResponseHeaders(200, 0);
}
@Test
public void shouldAddHeadersToResponse() throws Exception {
blinkResponse.header("content", "kuku");
blinkResponse.header("Accept", "popo");
apply();
assertThat(headers.get("content"), is(Arrays.asList("kuku")));
assertThat(headers.get("Accept"), is(Arrays.asList("popo")));
}
@Test
public void shouldAddCookieToResponse() throws IOException {
blinkResponse.cookie("myCookie", "zabo");
apply();
assertThat(headers.get("Set-Cookie"), is(Arrays.asList("myCookie=zabo")));
}
@Test
public void shouldAddNumberOfCookiesToResponse() throws IOException {
blinkResponse.cookie("myCookie", "zabo");
blinkResponse.cookie("mySecondCookie", "kuku");
apply();
assertThat(headers.get("Set-Cookie"), is(Arrays.asList("myCookie=zabo;mySecondCookie=kuku")));
}
@Test
public void shouldSetContentTypeHeader() throws Exception {
blinkResponse.type("application/json");
apply();
assertThat(headers.get(CONTENT_TYPE), is(Arrays.asList("application/json")));
}
@Test
public void shouldSetDefaultContentType() throws Exception {
apply();
assertThat(headers.get(CONTENT_TYPE), is(Arrays.asList(DEFAULT_CONTENT_TYPE)));
}
@Test
public void shouldRetrieveByteArray() throws Exception {
byte[] bytes = new byte[] {3, 2, 45, 23, 67, 12};
((HttpExchangeBlinkResponse)blinkResponse).setBody(bytes);
apply();
assertThat(responseOutputStream.toByteArray(), is(bytes));
}
} | package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.httpserver;
import IMPORT_1.junit.Before;
import IMPORT_1.junit.IMPORT_4;
import IMPORT_1.IMPORT_2.IMPORT_3.httpserver.HttpExchangeBlinkResponse;
import java.io.IMPORT_5;
import java.util.Arrays;
import static IMPORT_1.hamcrest.core.Is.IMPORT_6;
import static IMPORT_1.junit.Assert.*;
import static IMPORT_1.mockito.Matchers.any;
import static IMPORT_1.mockito.Mockito.*;
import static IMPORT_1.IMPORT_2.IMPORT_3.httpserver.HttpExchangeBlinkResponse.CONTENT_TYPE;
public class CLASS_0 extends AbstractHttpExchangeBlinkResponseTest {
private static final String VAR_0 = "app/json";
@Before
public void setUp() throws CLASS_1 {
super.setUp();
blinkResponse = new HttpExchangeBlinkResponse(VAR_0);
}
@IMPORT_4
public void FUNC_0() throws CLASS_1 {
FUNC_1();
FUNC_2(VAR_1.toString("UTF-8"), IMPORT_6(""));
}
@IMPORT_4
public void shouldHandleNullBody() throws CLASS_1 {
((HttpExchangeBlinkResponse)blinkResponse).FUNC_3(null);
FUNC_1();
FUNC_2(VAR_1.toString("UTF-8"), IMPORT_6(""));
}
@IMPORT_4
public void shouldSetStatusCode() throws CLASS_1 {
blinkResponse.status(404);
FUNC_1();
verify(httpExchange).sendResponseHeaders(404, 0);
}
@IMPORT_4
public void FUNC_4() throws CLASS_1 {
FUNC_1();
verify(httpExchange).sendResponseHeaders(200, 0);
}
@IMPORT_4
public void FUNC_5() throws CLASS_1 {
blinkResponse.header("content", "kuku");
blinkResponse.header("Accept", "popo");
FUNC_1();
FUNC_2(headers.get("content"), IMPORT_6(Arrays.asList("kuku")));
FUNC_2(headers.get("Accept"), IMPORT_6(Arrays.asList("popo")));
}
@IMPORT_4
public void shouldAddCookieToResponse() throws IMPORT_5 {
blinkResponse.FUNC_6("myCookie", "zabo");
FUNC_1();
FUNC_2(headers.get("Set-Cookie"), IMPORT_6(Arrays.asList("myCookie=zabo")));
}
@IMPORT_4
public void shouldAddNumberOfCookiesToResponse() throws IMPORT_5 {
blinkResponse.FUNC_6("myCookie", "zabo");
blinkResponse.FUNC_6("mySecondCookie", "kuku");
FUNC_1();
FUNC_2(headers.get("Set-Cookie"), IMPORT_6(Arrays.asList("myCookie=zabo;mySecondCookie=kuku")));
}
@IMPORT_4
public void shouldSetContentTypeHeader() throws CLASS_1 {
blinkResponse.type("application/json");
FUNC_1();
FUNC_2(headers.get(CONTENT_TYPE), IMPORT_6(Arrays.asList("application/json")));
}
@IMPORT_4
public void shouldSetDefaultContentType() throws CLASS_1 {
FUNC_1();
FUNC_2(headers.get(CONTENT_TYPE), IMPORT_6(Arrays.asList(VAR_0)));
}
@IMPORT_4
public void FUNC_7() throws CLASS_1 {
byte[] VAR_2 = new byte[] {3, 2, 45, 23, 67, 12};
((HttpExchangeBlinkResponse)blinkResponse).FUNC_3(VAR_2);
FUNC_1();
FUNC_2(VAR_1.FUNC_8(), IMPORT_6(VAR_2));
}
} | 0.344714 | {'IMPORT_0': 'test', 'IMPORT_1': 'org', 'IMPORT_2': 'rockm', 'IMPORT_3': 'blink', 'IMPORT_4': 'Test', 'IMPORT_5': 'IOException', 'IMPORT_6': 'is', 'CLASS_0': 'HttpExchangeBlinkResponseTest', 'VAR_0': 'DEFAULT_CONTENT_TYPE', 'CLASS_1': 'Exception', 'FUNC_0': 'bodyShouldNotBeNull', 'FUNC_1': 'apply', 'FUNC_2': 'assertThat', 'VAR_1': 'responseOutputStream', 'FUNC_3': 'setBody', 'FUNC_4': 'defaultStatusShouldBe200', 'FUNC_5': 'shouldAddHeadersToResponse', 'FUNC_6': 'cookie', 'FUNC_7': 'shouldRetrieveByteArray', 'VAR_2': 'bytes', 'FUNC_8': 'toByteArray'} | java | OOP | 26.29% |
/**
*
* @author Martin Gencur
*/
public class RESTEasyOperations implements RESTOperations {
private static final Log log = LogFactory.getLog(RESTEasyOperations.class);
private final RESTEasyService service;
public RESTEasyOperations(RESTEasyService service) {
this.service = service;
}
public RESTOperationInvoker getRESTInvoker(String contextPath) {
if (service.isRunning()) {
return new RESTOperationInvokerImpl(contextPath);
}
return null;
}
protected class RESTOperationInvokerImpl implements RESTOperationInvoker {
private String uri;
public RESTOperationInvokerImpl(String contextPath) {
this.uri = service.buildApplicationUrl(pickServer(), contextPath, service.getUsername(), service.getPassword());
}
/* There's one server picked for each thread at the beginning. Subsequent requests from this
thread go to the same server. */
private InetSocketAddress pickServer() {
return service.getServers().get(service.getServersLoadBalance().next(new Random()));
}
@Override
public Response get(List<Cookie> cookiesToPass, MultivaluedMap<String, Object> headersToPass) {
Response response = null;
if (service.isRunning()) {
try {
Invocation.Builder requestBuilder = service.getHttpClient().target(uri).request();
for (Cookie cookie : cookiesToPass) {
requestBuilder.cookie(cookie);
}
Invocation get = requestBuilder.accept(service.getContentType())
.buildGet();
response = get.invoke();
if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
log.warn("The requested URI does not exist");
}
} catch (Exception e) {
throw new RuntimeException("RESTEasyOperations::get request threw exception: " + uri, e);
} finally {
if (response != null) {
response.close();
}
}
}
return response;
}
}
} | /**
*
* @author Martin Gencur
*/
public class CLASS_0 implements CLASS_1 {
private static final CLASS_2 VAR_0 = VAR_1.FUNC_0(CLASS_0.class);
private final CLASS_3 VAR_2;
public CLASS_0(CLASS_3 VAR_2) {
this.VAR_2 = VAR_2;
}
public CLASS_4 FUNC_1(CLASS_5 VAR_3) {
if (VAR_2.FUNC_2()) {
return new CLASS_6(VAR_3);
}
return null;
}
protected class CLASS_6 implements CLASS_4 {
private CLASS_5 VAR_4;
public CLASS_6(CLASS_5 VAR_3) {
this.VAR_4 = VAR_2.FUNC_3(FUNC_4(), VAR_3, VAR_2.FUNC_5(), VAR_2.FUNC_6());
}
/* There's one server picked for each thread at the beginning. Subsequent requests from this
thread go to the same server. */
private CLASS_7 FUNC_4() {
return VAR_2.FUNC_7().FUNC_8(VAR_2.FUNC_9().FUNC_10(new CLASS_8()));
}
@Override
public CLASS_9 FUNC_8(CLASS_10<CLASS_11> cookiesToPass, CLASS_12<CLASS_5, CLASS_13> VAR_6) {
CLASS_9 VAR_7 = null;
if (VAR_2.FUNC_2()) {
try {
CLASS_14.Builder VAR_8 = VAR_2.FUNC_11().FUNC_12(VAR_4).FUNC_13();
for (CLASS_11 VAR_9 : cookiesToPass) {
VAR_8.FUNC_14(VAR_9);
}
CLASS_14 VAR_5 = VAR_8.FUNC_15(VAR_2.FUNC_16())
.FUNC_17();
VAR_7 = VAR_5.FUNC_18();
if (VAR_7.getStatus() == VAR_10.VAR_11.FUNC_19()) {
VAR_0.warn("The requested URI does not exist");
}
} catch (Exception VAR_12) {
throw new CLASS_15("RESTEasyOperations::get request threw exception: " + VAR_4, VAR_12);
} finally {
if (VAR_7 != null) {
VAR_7.FUNC_20();
}
}
}
return VAR_7;
}
}
} | 0.913215 | {'CLASS_0': 'RESTEasyOperations', 'CLASS_1': 'RESTOperations', 'CLASS_2': 'Log', 'VAR_0': 'log', 'VAR_1': 'LogFactory', 'FUNC_0': 'getLog', 'CLASS_3': 'RESTEasyService', 'VAR_2': 'service', 'CLASS_4': 'RESTOperationInvoker', 'FUNC_1': 'getRESTInvoker', 'CLASS_5': 'String', 'VAR_3': 'contextPath', 'FUNC_2': 'isRunning', 'CLASS_6': 'RESTOperationInvokerImpl', 'VAR_4': 'uri', 'FUNC_3': 'buildApplicationUrl', 'FUNC_4': 'pickServer', 'FUNC_5': 'getUsername', 'FUNC_6': 'getPassword', 'CLASS_7': 'InetSocketAddress', 'FUNC_7': 'getServers', 'FUNC_8': 'get', 'VAR_5': 'get', 'FUNC_9': 'getServersLoadBalance', 'FUNC_10': 'next', 'CLASS_8': 'Random', 'CLASS_9': 'Response', 'CLASS_10': 'List', 'CLASS_11': 'Cookie', 'CLASS_12': 'MultivaluedMap', 'CLASS_13': 'Object', 'VAR_6': 'headersToPass', 'VAR_7': 'response', 'CLASS_14': 'Invocation', 'VAR_8': 'requestBuilder', 'FUNC_11': 'getHttpClient', 'FUNC_12': 'target', 'FUNC_13': 'request', 'VAR_9': 'cookie', 'FUNC_14': 'cookie', 'FUNC_15': 'accept', 'FUNC_16': 'getContentType', 'FUNC_17': 'buildGet', 'FUNC_18': 'invoke', 'VAR_10': 'Status', 'VAR_11': 'NOT_FOUND', 'FUNC_19': 'getStatusCode', 'VAR_12': 'e', 'CLASS_15': 'RuntimeException', 'FUNC_20': 'close'} | java | OOP | 7.09% |
package br.com.tassioauad.spotifystreamer.view;
import java.util.List;
import br.com.tassioauad.spotifystreamer.model.entity.Track;
public interface TrackView {
void warnNoTracks();
void showPlayer(List<Track> trackList, int actualPosition);
}
| package br.com.IMPORT_0.spotifystreamer.IMPORT_1;
import IMPORT_2.IMPORT_3.List;
import br.com.IMPORT_0.spotifystreamer.IMPORT_4.entity.IMPORT_5;
public interface CLASS_0 {
void FUNC_0();
void showPlayer(List<IMPORT_5> VAR_0, int VAR_1);
}
| 0.454301 | {'IMPORT_0': 'tassioauad', 'IMPORT_1': 'view', 'IMPORT_2': 'java', 'IMPORT_3': 'util', 'IMPORT_4': 'model', 'IMPORT_5': 'Track', 'CLASS_0': 'TrackView', 'FUNC_0': 'warnNoTracks', 'VAR_0': 'trackList', 'VAR_1': 'actualPosition'} | java | Texto | 61.11% |
/**
* main method of server end
* @param args main arguments
*/
public static void main(String[] args) {
TextService service = new TextService(new TextDao());
Javalin app = Javalin.create(config -> {
config.registerPlugin(getConfiguredOpenApiPlugin());
}).start(7001);
app.get("/files/exists/:md5", service::handleExists);
app.post("/files/:md5", service::handleUpload);
app.get("/files/:md51/compare/:md52", service::handleCompare);
app.get("/files/:md5", service::handleDownload);
app.get("/", service::handleList);
} | /**
* main method of server end
* @param args main arguments
*/
public static void FUNC_0(String[] VAR_0) {
TextService VAR_1 = new TextService(new TextDao());
CLASS_0 VAR_3 = VAR_2.create(VAR_4 -> {
VAR_4.registerPlugin(FUNC_1());
}).FUNC_2(7001);
VAR_3.FUNC_3("/files/exists/:md5", VAR_1::VAR_5);
VAR_3.FUNC_4("/files/:md5", VAR_1::handleUpload);
VAR_3.FUNC_3("/files/:md51/compare/:md52", VAR_1::VAR_6);
VAR_3.FUNC_3("/files/:md5", VAR_1::VAR_7);
VAR_3.FUNC_3("/", VAR_1::VAR_8);
} | 0.739167 | {'FUNC_0': 'main', 'VAR_0': 'args', 'VAR_1': 'service', 'CLASS_0': 'Javalin', 'VAR_2': 'Javalin', 'VAR_3': 'app', 'VAR_4': 'config', 'FUNC_1': 'getConfiguredOpenApiPlugin', 'FUNC_2': 'start', 'FUNC_3': 'get', 'VAR_5': 'handleExists', 'FUNC_4': 'post', 'VAR_6': 'handleCompare', 'VAR_7': 'handleDownload', 'VAR_8': 'handleList'} | java | Procedural | 33.33% |
package com.shengsiyuan.multithreading;
/**
* 对象锁与静态锁
*
* @author by Zhangyichao
* @date 2019/11/1 14:12
* @see ThreadSynchronizedDemo
*/
public class ThreadSynchronizedDemo {
public static void main(String[] args) throws InterruptedException {
final ThreadSynchronizedObject object = new ThreadSynchronizedObject();
Thread thread_1 = new Thread("thread_1") {
public void run() {
try{
object.threadMethodA();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
};
Thread thread_2 = new Thread("thread_2") {
public void run() {
try{
object.threadMethodB();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
};
thread_1.start();
thread_2.start();
Thread.sleep(3000);
long start_time = (ThreadSynchronizedTimeUtils.mMethodAIntoTime - ThreadSynchronizedTimeUtils.mMethodBIntoTime) > 0 ? ThreadSynchronizedTimeUtils.mMethodAIntoTime
: ThreadSynchronizedTimeUtils.mMethodBIntoTime;
long end_time = (ThreadSynchronizedTimeUtils.mMethodAOutTime - ThreadSynchronizedTimeUtils.mMethodBOutTime) > 0 ? ThreadSynchronizedTimeUtils.mMethodAOutTime
: ThreadSynchronizedTimeUtils.mMethodBOutTime;
System.out.println("总耗时:" + (end_time - start_time));
}
}
class ThreadSynchronizedObject {
private Object object = new Object();
public synchronized void threadMethodA() throws InterruptedException {
ThreadSynchronizedTimeUtils.setMethodAIntoTime();
System.out.println(Thread.currentThread().getName() + ",进入threadMethodA");
Thread.sleep(1000); ///<模拟方法请求耗时
System.out.println(Thread.currentThread().getName() + ",退出threadMethodA");
ThreadSynchronizedTimeUtils.setMethodAOutTime();
}
public void threadMethodB() throws InterruptedException {
synchronized (this) {
ThreadSynchronizedTimeUtils.setMethodBIntoTime();
System.out.println(Thread.currentThread().getName() + ",进入threadMethodB");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + ",退出threadMethodB");
ThreadSynchronizedTimeUtils.setMethodBOutTime();
}
}
}
class ThreadSynchronizedTimeUtils {
public static long mMethodAIntoTime;
public static long mMethodAOutTime;
public static long mMethodBIntoTime;
public static long mMethodBOutTime;
public static void setMethodAIntoTime() {
mMethodAIntoTime = System.currentTimeMillis();
}
public static void setMethodAOutTime() {
mMethodAOutTime = System.currentTimeMillis();
}
public static void setMethodBIntoTime() {
mMethodBIntoTime = System.currentTimeMillis();
}
public static void setMethodBOutTime() {
mMethodBOutTime = System.currentTimeMillis();
}
}
| package com.shengsiyuan.multithreading;
/**
* 对象锁与静态锁
*
* @author by Zhangyichao
* @date 2019/11/1 14:12
* @see ThreadSynchronizedDemo
*/
public class ThreadSynchronizedDemo {
public static void main(String[] args) throws InterruptedException {
final ThreadSynchronizedObject object = new ThreadSynchronizedObject();
Thread thread_1 = new Thread("thread_1") {
public void run() {
try{
object.threadMethodA();
} catch (InterruptedException e) {
e.FUNC_0();
}
};
};
Thread thread_2 = new Thread("thread_2") {
public void run() {
try{
object.threadMethodB();
} catch (InterruptedException e) {
e.FUNC_0();
}
};
};
thread_1.start();
thread_2.start();
Thread.sleep(3000);
long start_time = (ThreadSynchronizedTimeUtils.mMethodAIntoTime - ThreadSynchronizedTimeUtils.mMethodBIntoTime) > 0 ? ThreadSynchronizedTimeUtils.mMethodAIntoTime
: ThreadSynchronizedTimeUtils.mMethodBIntoTime;
long end_time = (ThreadSynchronizedTimeUtils.mMethodAOutTime - ThreadSynchronizedTimeUtils.mMethodBOutTime) > 0 ? ThreadSynchronizedTimeUtils.mMethodAOutTime
: ThreadSynchronizedTimeUtils.mMethodBOutTime;
VAR_0.VAR_1.println("总耗时:" + (end_time - start_time));
}
}
class ThreadSynchronizedObject {
private Object object = new Object();
public synchronized void threadMethodA() throws InterruptedException {
ThreadSynchronizedTimeUtils.setMethodAIntoTime();
VAR_0.VAR_1.println(Thread.currentThread().getName() + ",进入threadMethodA");
Thread.sleep(1000); ///<模拟方法请求耗时
VAR_0.VAR_1.println(Thread.currentThread().getName() + ",退出threadMethodA");
ThreadSynchronizedTimeUtils.setMethodAOutTime();
}
public void threadMethodB() throws InterruptedException {
synchronized (this) {
ThreadSynchronizedTimeUtils.setMethodBIntoTime();
VAR_0.VAR_1.println(Thread.currentThread().getName() + ",进入threadMethodB");
Thread.sleep(1000);
VAR_0.VAR_1.println(Thread.currentThread().getName() + ",退出threadMethodB");
ThreadSynchronizedTimeUtils.setMethodBOutTime();
}
}
}
class ThreadSynchronizedTimeUtils {
public static long mMethodAIntoTime;
public static long mMethodAOutTime;
public static long mMethodBIntoTime;
public static long mMethodBOutTime;
public static void setMethodAIntoTime() {
mMethodAIntoTime = VAR_0.currentTimeMillis();
}
public static void setMethodAOutTime() {
mMethodAOutTime = VAR_0.currentTimeMillis();
}
public static void setMethodBIntoTime() {
mMethodBIntoTime = VAR_0.currentTimeMillis();
}
public static void setMethodBOutTime() {
mMethodBOutTime = VAR_0.currentTimeMillis();
}
}
| 0.047337 | {'FUNC_0': 'printStackTrace', 'VAR_0': 'System', 'VAR_1': 'out'} | java | error | 0 |
package com.mercadopago.android.px.addons.validator.internal;
import android.support.annotation.NonNull;
public interface Rule<T> {
boolean apply(@NonNull final T data);
} | package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.IMPORT_6;
import IMPORT_2.IMPORT_7.IMPORT_8.IMPORT_9;
public interface CLASS_0<T> {
boolean FUNC_0(@IMPORT_9 final T VAR_0);
} | 0.925215 | {'IMPORT_0': 'com', 'IMPORT_1': 'mercadopago', 'IMPORT_2': 'android', 'IMPORT_3': 'px', 'IMPORT_4': 'addons', 'IMPORT_5': 'validator', 'IMPORT_6': 'internal', 'IMPORT_7': 'support', 'IMPORT_8': 'annotation', 'IMPORT_9': 'NonNull', 'CLASS_0': 'Rule', 'FUNC_0': 'apply', 'VAR_0': 'data'} | java | Texto | 66.67% |
/**
* Class that implements functional interface {@link Command} and represents
* push command which puts current {@link TurtleState} state on stack modeled by
* {@link ObjectStack}.
*
* @author dbrcina
* @version 1.0
*
*/
public class PushCommand implements Command {
@Override
public void execute(Context ctx, Painter painter) {
ctx.pushState(ctx.getCurrentState().copy());
}
} | /**
* Class that implements functional interface {@link Command} and represents
* push command which puts current {@link TurtleState} state on stack modeled by
* {@link ObjectStack}.
*
* @author dbrcina
* @version 1.0
*
*/
public class CLASS_0 implements CLASS_1 {
@VAR_0
public void FUNC_0(Context VAR_1, CLASS_2 VAR_2) {
VAR_1.FUNC_1(VAR_1.FUNC_2().FUNC_3());
}
} | 0.898311 | {'CLASS_0': 'PushCommand', 'CLASS_1': 'Command', 'VAR_0': 'Override', 'FUNC_0': 'execute', 'VAR_1': 'ctx', 'CLASS_2': 'Painter', 'VAR_2': 'painter', 'FUNC_1': 'pushState', 'FUNC_2': 'getCurrentState', 'FUNC_3': 'copy'} | java | Texto | 9.68% |
/**
* go through each grant in the ACL
* - checks if the right/target of the grant matches the right/target of the grant
* and
* if the grantee type(specified by granteeFlags) is one of the grantee type
* we are interested in this call.
*
* - if so marks the right "seen" (so callsite default(only used by user right callsites)
* won't be honored)
* - check if the Account (the grantee parameter) matches the grantee of the grant
*
* @param acl
* @param granteeFlags For admin rights, because of negative grants and the more "specific"
* grantee takes precedence over the less "specific" grantee, we can't
* just do a single ZimbraACE.match to see if a grantee matches the grant.
* Instead, we need to check more specific grantee types first, then
* go on the the less specific ones. granteeFlags specifies the
* grantee type(s) we are checking for this call.
* e.g. an ACL has:
* adminA deny rightR - grant1
* groupG allow rightR - grant2
* and adminA is in groupG, we want to check grant1 before grant2.
*
* @return
* @throws ServiceException
*/
private Boolean checkPresetRight(List<ZimbraACE> acl, short granteeFlags, boolean subDomain)
throws ServiceException {
Boolean result = null;
for (ZimbraACE ace : acl) {
if (!matchesPresetRight(ace, granteeFlags, subDomain)) {
continue;
}
mSeenRight.setSeenRight();
if (ace.matchesGrantee(mGranteeAcct, !mRightNeeded.isUserRight())) {
return gotResult(ace);
}
}
return result;
} | /**
* go through each grant in the ACL
* - checks if the right/target of the grant matches the right/target of the grant
* and
* if the grantee type(specified by granteeFlags) is one of the grantee type
* we are interested in this call.
*
* - if so marks the right "seen" (so callsite default(only used by user right callsites)
* won't be honored)
* - check if the Account (the grantee parameter) matches the grantee of the grant
*
* @param acl
* @param granteeFlags For admin rights, because of negative grants and the more "specific"
* grantee takes precedence over the less "specific" grantee, we can't
* just do a single ZimbraACE.match to see if a grantee matches the grant.
* Instead, we need to check more specific grantee types first, then
* go on the the less specific ones. granteeFlags specifies the
* grantee type(s) we are checking for this call.
* e.g. an ACL has:
* adminA deny rightR - grant1
* groupG allow rightR - grant2
* and adminA is in groupG, we want to check grant1 before grant2.
*
* @return
* @throws ServiceException
*/
private CLASS_0 checkPresetRight(List<CLASS_1> VAR_0, short VAR_1, boolean subDomain)
throws ServiceException {
CLASS_0 result = null;
for (CLASS_1 ace : VAR_0) {
if (!FUNC_0(ace, VAR_1, subDomain)) {
continue;
}
mSeenRight.setSeenRight();
if (ace.FUNC_1(mGranteeAcct, !VAR_2.FUNC_2())) {
return FUNC_3(ace);
}
}
return result;
} | 0.412985 | {'CLASS_0': 'Boolean', 'CLASS_1': 'ZimbraACE', 'VAR_0': 'acl', 'VAR_1': 'granteeFlags', 'FUNC_0': 'matchesPresetRight', 'FUNC_1': 'matchesGrantee', 'VAR_2': 'mRightNeeded', 'FUNC_2': 'isUserRight', 'FUNC_3': 'gotResult'} | java | Procedural | 22.22% |
package android.support.v7.widget;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
class a
extends Drawable
{
final ActionBarContainer a;
public a(ActionBarContainer paramActionBarContainer)
{
this.a = paramActionBarContainer;
}
public void draw(Canvas paramCanvas)
{
if (this.a.mIsSplit)
{
if (this.a.mSplitBackground != null) {
this.a.mSplitBackground.draw(paramCanvas);
}
}
else
{
if (this.a.mBackground != null) {
this.a.mBackground.draw(paramCanvas);
}
if ((this.a.mStackedBackground != null) && (this.a.mIsStacked)) {
this.a.mStackedBackground.draw(paramCanvas);
}
}
}
public int getOpacity()
{
return 0;
}
public void setAlpha(int paramInt) {}
public void setColorFilter(ColorFilter paramColorFilter) {}
}
/* Location: ~/android/support/v7/widget/a.class
*
* Reversed by: J
*/ | package IMPORT_0.IMPORT_1.v7.widget;
import IMPORT_0.graphics.Canvas;
import IMPORT_0.graphics.ColorFilter;
import IMPORT_0.graphics.drawable.Drawable;
class a
extends Drawable
{
final ActionBarContainer a;
public a(ActionBarContainer paramActionBarContainer)
{
this.a = paramActionBarContainer;
}
public void draw(Canvas paramCanvas)
{
if (this.a.mIsSplit)
{
if (this.a.mSplitBackground != null) {
this.a.mSplitBackground.draw(paramCanvas);
}
}
else
{
if (this.a.VAR_0 != null) {
this.a.VAR_0.draw(paramCanvas);
}
if ((this.a.mStackedBackground != null) && (this.a.VAR_1)) {
this.a.mStackedBackground.draw(paramCanvas);
}
}
}
public int getOpacity()
{
return 0;
}
public void setAlpha(int paramInt) {}
public void setColorFilter(ColorFilter VAR_2) {}
}
/* Location: ~/android/support/v7/widget/a.class
*
* Reversed by: J
*/ | 0.125896 | {'IMPORT_0': 'android', 'IMPORT_1': 'support', 'VAR_0': 'mBackground', 'VAR_1': 'mIsStacked', 'VAR_2': 'paramColorFilter'} | java | OOP | 60.40% |
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LiteCartAdminLoginPage {
private WebDriver driver;
public LiteCartAdminLoginPage(WebDriver driver) {
this.driver = driver;
}
private By userNameField = By.xpath("//input[@name='username']");
private By userPassField = By.xpath("//input[@name='password']");
private By rememberCheckBox = By.xpath("//inpute[@name='remember_me']");
private By loginButton = By.xpath("//button[@type='submit']");
private By emptyUserNameFieldError = By.xpath("//div[@class='alert alert-danger' and contains(text(),'You must provide a username')]");
private By userCouldNotFoundError = By.xpath("//div[@class='alert alert-danger' and contains(text(),'The user could')]");
private By wrongCombinationUserPass = By.xpath("//div[@class='alert alert-danger' and contains(text(),'Wrong combination')]");
private By attempsWarningError = By.xpath("//div[@class='alert alert-danger' and contains(text(),'login attempts left until your account')]");
private By accountBlockedError = By.xpath("//div[@class='alert alert-danger' and contains(text(),'The account has been temporary blocked 15 minutes')]");
private By accountBlockedUntil = By.xpath("//div[@class='alert alert-danger' and contains(text(),'The account is blocked until')]");
private By imgLogo = By.xpath("//div[@class='header']//img");
private By logoIcon = By.xpath("//div[@class='header']/a");
public LiteCartAdminLoginPage typeUserNameField(String userName){
driver.findElement(userNameField).sendKeys(userName);
return this;
}
public WebElement getTheLogo(){
return driver.findElement(imgLogo);
}
public boolean isHaveTheLogo(){
try {
getTheLogo();
return true;
}catch (NoSuchElementException e){
return false;
}
}
public LiteCartAdminLoginPage typePassNameField(String password){
driver.findElement(userPassField).sendKeys(password);
return this;
}
public boolean testCheckBoxIsSelected(){
if (driver.findElement(rememberCheckBox).isSelected()) return true;
else return false;
}
public LiteCartAdminLoginPage selectCheckBox(){
if (testCheckBoxIsSelected() == false){
driver.findElement(rememberCheckBox).click();
}
return this;
}
public LiteCartAdminLoginPage loginWithEmptyFields(){
driver.findElement(loginButton).click();
return new LiteCartAdminLoginPage(driver);
}
public LiteCartAdminLoginPage loginWithEmptyPass(String userName){
typeUserNameField(userName);
driver.findElement(loginButton).click();
return new LiteCartAdminLoginPage(driver);
}
public LiteCartAdminLoginPage loginWithIncorrectUserName(String incorrectUserName){
typeUserNameField(incorrectUserName);
driver.findElement(loginButton).click();
return new LiteCartAdminLoginPage(driver);
}
public LiteCartAdminLoginPage loginWithIncorrectPass(String userName, String incorrectPass){
typeUserNameField(userName);
typePassNameField(incorrectPass);
driver.findElement(loginButton).click();
return new LiteCartAdminLoginPage(driver);
}
public LiteCartAdminPage successLogin(String userName, String password){
typeUserNameField(userName);
typePassNameField(password);
driver.findElement(loginButton).click();
return new LiteCartAdminPage(driver);
}
public LiteCartUserPage clickOnLogoIcon(){
driver.findElement(logoIcon).click();
return new LiteCartUserPage(driver);
}
}
| import org.openqa.IMPORT_0.IMPORT_1;
import org.openqa.IMPORT_0.IMPORT_2;
import org.openqa.IMPORT_0.WebDriver;
import org.openqa.IMPORT_0.IMPORT_3;
public class CLASS_0 {
private WebDriver VAR_0;
public CLASS_0(WebDriver VAR_0) {
this.VAR_0 = VAR_0;
}
private IMPORT_1 VAR_1 = IMPORT_1.FUNC_0("//input[@name='username']");
private IMPORT_1 VAR_2 = IMPORT_1.FUNC_0("//input[@name='password']");
private IMPORT_1 VAR_3 = IMPORT_1.FUNC_0("//inpute[@name='remember_me']");
private IMPORT_1 VAR_4 = IMPORT_1.FUNC_0("//button[@type='submit']");
private IMPORT_1 VAR_5 = IMPORT_1.FUNC_0("//div[@class='alert alert-danger' and contains(text(),'You must provide a username')]");
private IMPORT_1 VAR_6 = IMPORT_1.FUNC_0("//div[@class='alert alert-danger' and contains(text(),'The user could')]");
private IMPORT_1 VAR_7 = IMPORT_1.FUNC_0("//div[@class='alert alert-danger' and contains(text(),'Wrong combination')]");
private IMPORT_1 VAR_8 = IMPORT_1.FUNC_0("//div[@class='alert alert-danger' and contains(text(),'login attempts left until your account')]");
private IMPORT_1 VAR_9 = IMPORT_1.FUNC_0("//div[@class='alert alert-danger' and contains(text(),'The account has been temporary blocked 15 minutes')]");
private IMPORT_1 VAR_10 = IMPORT_1.FUNC_0("//div[@class='alert alert-danger' and contains(text(),'The account is blocked until')]");
private IMPORT_1 VAR_11 = IMPORT_1.FUNC_0("//div[@class='header']//img");
private IMPORT_1 VAR_12 = IMPORT_1.FUNC_0("//div[@class='header']/a");
public CLASS_0 FUNC_1(CLASS_1 VAR_13){
VAR_0.FUNC_2(VAR_1).FUNC_3(VAR_13);
return this;
}
public IMPORT_3 FUNC_4(){
return VAR_0.FUNC_2(VAR_11);
}
public boolean FUNC_5(){
try {
FUNC_4();
return true;
}catch (IMPORT_2 VAR_14){
return false;
}
}
public CLASS_0 FUNC_6(CLASS_1 VAR_15){
VAR_0.FUNC_2(VAR_2).FUNC_3(VAR_15);
return this;
}
public boolean FUNC_7(){
if (VAR_0.FUNC_2(VAR_3).FUNC_8()) return true;
else return false;
}
public CLASS_0 FUNC_9(){
if (FUNC_7() == false){
VAR_0.FUNC_2(VAR_3).FUNC_10();
}
return this;
}
public CLASS_0 loginWithEmptyFields(){
VAR_0.FUNC_2(VAR_4).FUNC_10();
return new CLASS_0(VAR_0);
}
public CLASS_0 FUNC_11(CLASS_1 VAR_13){
FUNC_1(VAR_13);
VAR_0.FUNC_2(VAR_4).FUNC_10();
return new CLASS_0(VAR_0);
}
public CLASS_0 loginWithIncorrectUserName(CLASS_1 VAR_16){
FUNC_1(VAR_16);
VAR_0.FUNC_2(VAR_4).FUNC_10();
return new CLASS_0(VAR_0);
}
public CLASS_0 FUNC_12(CLASS_1 VAR_13, CLASS_1 VAR_17){
FUNC_1(VAR_13);
FUNC_6(VAR_17);
VAR_0.FUNC_2(VAR_4).FUNC_10();
return new CLASS_0(VAR_0);
}
public CLASS_2 FUNC_13(CLASS_1 VAR_13, CLASS_1 VAR_15){
FUNC_1(VAR_13);
FUNC_6(VAR_15);
VAR_0.FUNC_2(VAR_4).FUNC_10();
return new CLASS_2(VAR_0);
}
public LiteCartUserPage FUNC_14(){
VAR_0.FUNC_2(VAR_12).FUNC_10();
return new LiteCartUserPage(VAR_0);
}
}
| 0.833758 | {'IMPORT_0': 'selenium', 'IMPORT_1': 'By', 'IMPORT_2': 'NoSuchElementException', 'IMPORT_3': 'WebElement', 'CLASS_0': 'LiteCartAdminLoginPage', 'VAR_0': 'driver', 'VAR_1': 'userNameField', 'FUNC_0': 'xpath', 'VAR_2': 'userPassField', 'VAR_3': 'rememberCheckBox', 'VAR_4': 'loginButton', 'VAR_5': 'emptyUserNameFieldError', 'VAR_6': 'userCouldNotFoundError', 'VAR_7': 'wrongCombinationUserPass', 'VAR_8': 'attempsWarningError', 'VAR_9': 'accountBlockedError', 'VAR_10': 'accountBlockedUntil', 'VAR_11': 'imgLogo', 'VAR_12': 'logoIcon', 'FUNC_1': 'typeUserNameField', 'CLASS_1': 'String', 'VAR_13': 'userName', 'FUNC_2': 'findElement', 'FUNC_3': 'sendKeys', 'FUNC_4': 'getTheLogo', 'FUNC_5': 'isHaveTheLogo', 'VAR_14': 'e', 'FUNC_6': 'typePassNameField', 'VAR_15': 'password', 'FUNC_7': 'testCheckBoxIsSelected', 'FUNC_8': 'isSelected', 'FUNC_9': 'selectCheckBox', 'FUNC_10': 'click', 'FUNC_11': 'loginWithEmptyPass', 'VAR_16': 'incorrectUserName', 'FUNC_12': 'loginWithIncorrectPass', 'VAR_17': 'incorrectPass', 'CLASS_2': 'LiteCartAdminPage', 'FUNC_13': 'successLogin', 'FUNC_14': 'clickOnLogoIcon'} | java | error | 0 |
package org.nightvoyager.app.entity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.nightvoyager.core.data.IPersonInfo;
import org.nightvoyager.core.security.IPermissionComponent;
import org.nightvoyager.core.security.IPermissionSet;
import org.nightvoyager.core.security.Permissions;
import javax.naming.OperationNotSupportedException;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Arrays;
@Entity
@Table(name = "persons")
public class PersonInfo implements IPersonInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name = "permissions", nullable = false)
private String permissions = Permissions.toString(Permissions.DEFAULT_CANDIDATE_PERMISSIONS);
@Column(nullable = false)
private String name = "";
@Column(nullable = false)
private String passwd;
private String[] getPermissionsAsArray(){
return new String[0];
}
@NotNull
@Override
public long getId() {
return this.id;
}
/**
* Create by <see>IPersonInfo</see>
* @param personInfo
*/
private PersonInfo(IPersonInfo personInfo) {
this.id = personInfo.getId();
try {
this.setName(personInfo.getName());
} catch (OperationNotSupportedException e) {
e.printStackTrace();
}
}
/**
* Preparing for ORM framework
* DO NOT USE THIS CONSTRUCTOR for create new instance manually
*/
public PersonInfo() {
}
public static PersonInfo valueOf(IPersonInfo personInfo) {
if (personInfo instanceof PersonInfo) {
return (PersonInfo) personInfo;
} else {
return new PersonInfo(personInfo);
}
}
@NotNull
@Override
public String getName() {
return this.name;
}
@Override
public void setName(String name) throws OperationNotSupportedException {
this.name = name;
}
public String getPassword() {
return passwd;
}
@Nullable
@Override
public IPermissionComponent getPermissionParent() {
return null;
}
@NotNull
@Override
public IPermissionSet getSelfPermissionSet() {
return null;
}
}
| package IMPORT_0.IMPORT_1.IMPORT_2.entity;
import IMPORT_0.IMPORT_3.IMPORT_4.IMPORT_5;
import IMPORT_0.IMPORT_3.IMPORT_4.Nullable;
import IMPORT_0.IMPORT_1.core.IMPORT_6.IPersonInfo;
import IMPORT_0.IMPORT_1.core.IMPORT_7.IMPORT_8;
import IMPORT_0.IMPORT_1.core.IMPORT_7.IMPORT_9;
import IMPORT_0.IMPORT_1.core.IMPORT_7.Permissions;
import javax.IMPORT_10.IMPORT_11;
import javax.IMPORT_12.*;
import java.IMPORT_13.IMPORT_14;
import java.IMPORT_13.Arrays;
@VAR_0
@VAR_1(name = "persons")
public class PersonInfo implements IPersonInfo {
@VAR_2
@VAR_3(VAR_4 = GenerationType.VAR_5)
@Column(name = "id")
private long id;
@Column(name = "permissions", VAR_6 = false)
private String permissions = Permissions.toString(Permissions.VAR_7);
@Column(VAR_6 = false)
private String name = "";
@Column(VAR_6 = false)
private String VAR_8;
private String[] FUNC_0(){
return new String[0];
}
@IMPORT_5
@VAR_9
public long FUNC_1() {
return this.id;
}
/**
* Create by <see>IPersonInfo</see>
* @param personInfo
*/
private PersonInfo(IPersonInfo personInfo) {
this.id = personInfo.FUNC_1();
try {
this.FUNC_2(personInfo.FUNC_3());
} catch (IMPORT_11 e) {
e.FUNC_4();
}
}
/**
* Preparing for ORM framework
* DO NOT USE THIS CONSTRUCTOR for create new instance manually
*/
public PersonInfo() {
}
public static PersonInfo FUNC_5(IPersonInfo personInfo) {
if (personInfo instanceof PersonInfo) {
return (PersonInfo) personInfo;
} else {
return new PersonInfo(personInfo);
}
}
@IMPORT_5
@VAR_9
public String FUNC_3() {
return this.name;
}
@VAR_9
public void FUNC_2(String name) throws IMPORT_11 {
this.name = name;
}
public String FUNC_6() {
return VAR_8;
}
@Nullable
@VAR_9
public IMPORT_8 getPermissionParent() {
return null;
}
@IMPORT_5
@VAR_9
public IMPORT_9 getSelfPermissionSet() {
return null;
}
}
| 0.642133 | {'IMPORT_0': 'org', 'IMPORT_1': 'nightvoyager', 'IMPORT_2': 'app', 'IMPORT_3': 'jetbrains', 'IMPORT_4': 'annotations', 'IMPORT_5': 'NotNull', 'IMPORT_6': 'data', 'IMPORT_7': 'security', 'IMPORT_8': 'IPermissionComponent', 'IMPORT_9': 'IPermissionSet', 'IMPORT_10': 'naming', 'IMPORT_11': 'OperationNotSupportedException', 'IMPORT_12': 'persistence', 'IMPORT_13': 'util', 'IMPORT_14': 'ArrayList', 'VAR_0': 'Entity', 'VAR_1': 'Table', 'VAR_2': 'Id', 'VAR_3': 'GeneratedValue', 'VAR_4': 'strategy', 'VAR_5': 'IDENTITY', 'VAR_6': 'nullable', 'VAR_7': 'DEFAULT_CANDIDATE_PERMISSIONS', 'VAR_8': 'passwd', 'FUNC_0': 'getPermissionsAsArray', 'VAR_9': 'Override', 'FUNC_1': 'getId', 'FUNC_2': 'setName', 'FUNC_3': 'getName', 'FUNC_4': 'printStackTrace', 'FUNC_5': 'valueOf', 'FUNC_6': 'getPassword'} | java | Hibrido | 55.94% |
/**
* @return the next element in the iteration.
*/
public T next() {
if (pushedElement != null) {
final T ret = pushedElement;
pushedElement = null;
return ret;
} else {
return underlyingIterator.next();
}
} | /**
* @return the next element in the iteration.
*/
public CLASS_0 FUNC_0() {
if (VAR_0 != null) {
final CLASS_0 VAR_1 = VAR_0;
VAR_0 = null;
return VAR_1;
} else {
return VAR_2.FUNC_0();
}
} | 0.939269 | {'CLASS_0': 'T', 'FUNC_0': 'next', 'VAR_0': 'pushedElement', 'VAR_1': 'ret', 'VAR_2': 'underlyingIterator'} | java | Procedural | 100.00% |
/**
* The DOMImplementation class is description of a particular
* implementation of the Document Object Model. As such its data is
* static, shared by all instances of this implementation.
* <P>
* The DOM API requires that it be a real object rather than static
* methods. However, there's nothing that says it can't be a singleton,
* so that's how I've implemented it.
* <P>
* This particular class, along with DocumentImpl, supports the DOM
* Core, DOM Level 2 optional mofules, and Abstract Schemas (Experimental).
* @deprecated
* @version $Id$
* @since PR-DOM-Level-1-19980818.
*/
public class ASDOMImplementationImpl extends DOMImplementationImpl
implements DOMImplementationAS {
// static
/** Dom implementation singleton. */
static final ASDOMImplementationImpl singleton = new ASDOMImplementationImpl();
//
// Public methods
//
/** NON-DOM: Obtain and return the single shared object */
public static DOMImplementation getDOMImplementation() {
return singleton;
}
//
// DOM L3 Abstract Schemas:
// REVISIT: implement hasFeature()
//
/**
* DOM Level 3 WD - Experimental.
* Creates an ASModel.
* @param isNamespaceAware Allow creation of <code>ASModel</code> with
* this attribute set to a specific value.
* @return A <code>null</code> return indicates failure.what is a
* failure? Could be a system error.
*/
public ASModel createAS(boolean isNamespaceAware){
return new ASModelImpl(isNamespaceAware);
}
/**
* DOM Level 3 WD - Experimental.
* Creates an <code>DOMASBuilder</code>.Do we need the method since we
* already have <code>DOMImplementationLS.createDOMParser</code>?
* @return DOMASBuilder
*/
public DOMASBuilder createDOMASBuilder(){
return new DOMASBuilderImpl();
}
/**
* DOM Level 3 WD - Experimental.
* Creates an <code>DOMASWriter</code>.
* @return a DOMASWriter
*/
public DOMASWriter createDOMASWriter(){
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_SUPPORTED_ERR", null);
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
} | /**
* The DOMImplementation class is description of a particular
* implementation of the Document Object Model. As such its data is
* static, shared by all instances of this implementation.
* <P>
* The DOM API requires that it be a real object rather than static
* methods. However, there's nothing that says it can't be a singleton,
* so that's how I've implemented it.
* <P>
* This particular class, along with DocumentImpl, supports the DOM
* Core, DOM Level 2 optional mofules, and Abstract Schemas (Experimental).
* @deprecated
* @version $Id$
* @since PR-DOM-Level-1-19980818.
*/
public class CLASS_0 extends CLASS_1
implements CLASS_2 {
// static
/** Dom implementation singleton. */
static final CLASS_0 VAR_0 = new CLASS_0();
//
// Public methods
//
/** NON-DOM: Obtain and return the single shared object */
public static CLASS_3 getDOMImplementation() {
return VAR_0;
}
//
// DOM L3 Abstract Schemas:
// REVISIT: implement hasFeature()
//
/**
* DOM Level 3 WD - Experimental.
* Creates an ASModel.
* @param isNamespaceAware Allow creation of <code>ASModel</code> with
* this attribute set to a specific value.
* @return A <code>null</code> return indicates failure.what is a
* failure? Could be a system error.
*/
public ASModel FUNC_0(boolean VAR_1){
return new CLASS_4(VAR_1);
}
/**
* DOM Level 3 WD - Experimental.
* Creates an <code>DOMASBuilder</code>.Do we need the method since we
* already have <code>DOMImplementationLS.createDOMParser</code>?
* @return DOMASBuilder
*/
public CLASS_5 FUNC_1(){
return new CLASS_6();
}
/**
* DOM Level 3 WD - Experimental.
* Creates an <code>DOMASWriter</code>.
* @return a DOMASWriter
*/
public CLASS_7 FUNC_2(){
CLASS_8 VAR_2 = DOMMessageFormatter.FUNC_3(DOMMessageFormatter.VAR_3, "NOT_SUPPORTED_ERR", null);
throw new CLASS_9(VAR_4.VAR_5, VAR_2);
}
} | 0.879401 | {'CLASS_0': 'ASDOMImplementationImpl', 'CLASS_1': 'DOMImplementationImpl', 'CLASS_2': 'DOMImplementationAS', 'VAR_0': 'singleton', 'CLASS_3': 'DOMImplementation', 'FUNC_0': 'createAS', 'VAR_1': 'isNamespaceAware', 'CLASS_4': 'ASModelImpl', 'CLASS_5': 'DOMASBuilder', 'FUNC_1': 'createDOMASBuilder', 'CLASS_6': 'DOMASBuilderImpl', 'CLASS_7': 'DOMASWriter', 'FUNC_2': 'createDOMASWriter', 'CLASS_8': 'String', 'VAR_2': 'msg', 'FUNC_3': 'formatMessage', 'VAR_3': 'DOM_DOMAIN', 'CLASS_9': 'DOMException', 'VAR_4': 'DOMException', 'VAR_5': 'NOT_SUPPORTED_ERR'} | java | OOP | 100.00% |
/**
* Test all combinations and permutations of valid formula syntax/semantics
*
* @author dchasman
* @since 140
*/
public class ParserTest extends ParserTestBase {
public ParserTest(String name) {
super(name);
}
public void testCaseInsensitivity() throws FormulaException {
parseTest("abs(1)", " ( abs 1 )");
parseTest("ABS(1)", " ( ABS 1 )");
parseTest("Abs(1)", " ( Abs 1 )");
}
public void testConstant() throws FormulaException {
parseTest("true", " true");
parseTest("false", " false");
}
public void testStringConstant() throws FormulaException {
parseTest("\"mothra\"", " \"mothra\"");
}
public void testAdd() throws FormulaException {
testBinaryOperator("+");
}
public void testSubtract() throws FormulaException {
testBinaryOperator("-");
}
public void testMultiply() throws FormulaException {
testBinaryOperator("*");
}
public void testDivide() throws FormulaException {
testBinaryOperator("/");
}
public void testUnaryMinus() throws FormulaException {
parseTest("-2", " ( - 2 )");
}
public void testUnaryPlus() throws FormulaException {
parseTest("+2", " ( + 2 )");
}
public void testFieldReference() throws FormulaException {
parseTest("a", " a");
}
public void testGT() throws FormulaException {
testBinaryOperator(">");
}
public void testGTEQ() throws FormulaException {
testBinaryOperator(">=");
}
public void testLTEQ() throws FormulaException {
testBinaryOperator("<=");
}
public void testIf() throws FormulaException {
parseTest("if (temperature > 1000, 98.6, temperature)", " ( if ( > temperature 1000 ) 98.6 temperature )");
}
public void testPrecedence() throws FormulaException {
parseTest("(1 + 2) * (3 + 4) / 2", " ( / ( * ( + 1 2 ) ( + 3 4 ) ) 2 )");
parseTest("1 + 2 * 3 + 4 / 2", " ( + ( + 1 ( * 2 3 ) ) ( / 4 2 ) )");
}
public void testWhitespace() throws FormulaException {
parseTest("WON:Sum /( CLOSED:Sum - WON:Sum) * 100", " ( * ( / WON:Sum ( - CLOSED:Sum WON:Sum ) ) 100 )");
parseTest("WON:Sum / ( CLOSED:Sum - WON:Sum) * 100", " ( * ( / WON:Sum ( - CLOSED:Sum WON:Sum ) ) 100 )");
parseTest("IF(Probability = 1, ROUND(Amount * 0.02, 2) , 0)",
" ( IF ( = Probability 1 ) ( ROUND ( * Amount 0.02 ) 2 ) 0 )");
}
public void testGarbage() throws FormulaException {
try {
parseTest("AMOUNT:Sum dsa* saaa11- df", null);
fail();
}
catch (Exception e) {}
try {
parseTest("1 + 2 garbage", null);
fail();
}
catch (Exception e) {}
try {
parseTest("garbage 1 + 2", null);
fail();
}
catch (Exception e) {}
}
public void testSpecialCharacters() throws FormulaException {
parseTest("\"Hello \\\"cruel\\\" world\"", " \"Hello \\\"cruel\\\" world\"");
}
private void testBinaryOperator(String operator) throws FormulaException {
for (int i = 0; i < lhs.length; i++) {
for (int j = 0; j < rhs.length; j++) {
parseTest(lhs[i] + " " + operator + " " + rhs[j], " ( " + operator + " " + fieldName(lhs[i]) + " "
+ fieldName(rhs[j]) + " )");
}
}
}
private String[] lhs = { "1", "a", "\"foo\"", "true" };
private String[] rhs = { "2", "b", "\"bar\"", "false" };
} | /**
* Test all combinations and permutations of valid formula syntax/semantics
*
* @author dchasman
* @since 140
*/
public class CLASS_0 extends CLASS_1 {
public CLASS_0(CLASS_2 VAR_0) {
super(VAR_0);
}
public void FUNC_0() throws CLASS_3 {
FUNC_1("abs(1)", " ( abs 1 )");
FUNC_1("ABS(1)", " ( ABS 1 )");
FUNC_1("Abs(1)", " ( Abs 1 )");
}
public void FUNC_2() throws CLASS_3 {
FUNC_1("true", " true");
FUNC_1("false", " false");
}
public void FUNC_3() throws CLASS_3 {
FUNC_1("\"mothra\"", " \"mothra\"");
}
public void FUNC_4() throws CLASS_3 {
FUNC_5("+");
}
public void FUNC_6() throws CLASS_3 {
FUNC_5("-");
}
public void FUNC_7() throws CLASS_3 {
FUNC_5("*");
}
public void FUNC_8() throws CLASS_3 {
FUNC_5("/");
}
public void FUNC_9() throws CLASS_3 {
FUNC_1("-2", " ( - 2 )");
}
public void FUNC_10() throws CLASS_3 {
FUNC_1("+2", " ( + 2 )");
}
public void FUNC_11() throws CLASS_3 {
FUNC_1("a", " a");
}
public void FUNC_12() throws CLASS_3 {
FUNC_5(">");
}
public void FUNC_13() throws CLASS_3 {
FUNC_5(">=");
}
public void FUNC_14() throws CLASS_3 {
FUNC_5("<=");
}
public void FUNC_15() throws CLASS_3 {
FUNC_1("if (temperature > 1000, 98.6, temperature)", " ( if ( > temperature 1000 ) 98.6 temperature )");
}
public void FUNC_16() throws CLASS_3 {
FUNC_1("(1 + 2) * (3 + 4) / 2", " ( / ( * ( + 1 2 ) ( + 3 4 ) ) 2 )");
FUNC_1("1 + 2 * 3 + 4 / 2", " ( + ( + 1 ( * 2 3 ) ) ( / 4 2 ) )");
}
public void FUNC_17() throws CLASS_3 {
FUNC_1("WON:Sum /( CLOSED:Sum - WON:Sum) * 100", " ( * ( / WON:Sum ( - CLOSED:Sum WON:Sum ) ) 100 )");
FUNC_1("WON:Sum / ( CLOSED:Sum - WON:Sum) * 100", " ( * ( / WON:Sum ( - CLOSED:Sum WON:Sum ) ) 100 )");
FUNC_1("IF(Probability = 1, ROUND(Amount * 0.02, 2) , 0)",
" ( IF ( = Probability 1 ) ( ROUND ( * Amount 0.02 ) 2 ) 0 )");
}
public void FUNC_18() throws CLASS_3 {
try {
FUNC_1("AMOUNT:Sum dsa* saaa11- df", null);
FUNC_19();
}
catch (CLASS_4 VAR_1) {}
try {
FUNC_1("1 + 2 garbage", null);
FUNC_19();
}
catch (CLASS_4 VAR_1) {}
try {
FUNC_1("garbage 1 + 2", null);
FUNC_19();
}
catch (CLASS_4 VAR_1) {}
}
public void FUNC_20() throws CLASS_3 {
FUNC_1("\"Hello \\\"cruel\\\" world\"", " \"Hello \\\"cruel\\\" world\"");
}
private void FUNC_5(CLASS_2 VAR_2) throws CLASS_3 {
for (int VAR_3 = 0; VAR_3 < VAR_4.VAR_5; VAR_3++) {
for (int VAR_6 = 0; VAR_6 < VAR_7.VAR_5; VAR_6++) {
FUNC_1(VAR_4[VAR_3] + " " + VAR_2 + " " + VAR_7[VAR_6], " ( " + VAR_2 + " " + FUNC_21(VAR_4[VAR_3]) + " "
+ FUNC_21(VAR_7[VAR_6]) + " )");
}
}
}
private CLASS_2[] VAR_4 = { "1", "a", "\"foo\"", "true" };
private CLASS_2[] VAR_7 = { "2", "b", "\"bar\"", "false" };
} | 0.99838 | {'CLASS_0': 'ParserTest', 'CLASS_1': 'ParserTestBase', 'CLASS_2': 'String', 'VAR_0': 'name', 'FUNC_0': 'testCaseInsensitivity', 'CLASS_3': 'FormulaException', 'FUNC_1': 'parseTest', 'FUNC_2': 'testConstant', 'FUNC_3': 'testStringConstant', 'FUNC_4': 'testAdd', 'FUNC_5': 'testBinaryOperator', 'FUNC_6': 'testSubtract', 'FUNC_7': 'testMultiply', 'FUNC_8': 'testDivide', 'FUNC_9': 'testUnaryMinus', 'FUNC_10': 'testUnaryPlus', 'FUNC_11': 'testFieldReference', 'FUNC_12': 'testGT', 'FUNC_13': 'testGTEQ', 'FUNC_14': 'testLTEQ', 'FUNC_15': 'testIf', 'FUNC_16': 'testPrecedence', 'FUNC_17': 'testWhitespace', 'FUNC_18': 'testGarbage', 'FUNC_19': 'fail', 'CLASS_4': 'Exception', 'VAR_1': 'e', 'FUNC_20': 'testSpecialCharacters', 'VAR_2': 'operator', 'VAR_3': 'i', 'VAR_4': 'lhs', 'VAR_5': 'length', 'VAR_6': 'j', 'VAR_7': 'rhs', 'FUNC_21': 'fieldName'} | java | OOP | 93.49% |
package com.splunk.logging.log4j2.appender;
import java.io.Serializable;
import java.util.concurrent.locks.*;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.core.*;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.appender.AppenderLoggingException;
import org.apache.logging.log4j.core.config.plugins.*;
import com.splunk.logging.HECTransportConfig;
import com.splunk.logging.SplunkHECInput;
@Plugin(name = "SplunkHECAppender", category = "Core", elementType = "appender", printObject = true)
public final class SplunkHECAppender extends AbstractAppender {
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Lock readLock = rwLock.readLock();
// connection settings
private HECTransportConfig config;
// queuing settings
private String maxQueueSize;
private boolean dropEventsOnQueueFull;
private SplunkHECInput shi;
protected SplunkHECAppender(String name, HECTransportConfig config,
boolean dropEventsOnQueueFull, String maxQueueSize, Filter filter,
Layout<? extends Serializable> layout,
final boolean ignoreExceptions) {
super(name, filter, layout, ignoreExceptions);
this.config = config;
try {
this.shi = new SplunkHECInput(config);
this.shi.setMaxQueueSize(maxQueueSize);
this.shi.setDropEventsOnQueueFull(dropEventsOnQueueFull);
} catch (Exception e) {
}
}
@Override
public void append(LogEvent event) {
readLock.lock();
try {
try {
if (shi == null) {
shi = new SplunkHECInput(config);
shi.setMaxQueueSize(maxQueueSize);
shi.setDropEventsOnQueueFull(dropEventsOnQueueFull);
}
} catch (Exception e) {
throw new AppenderLoggingException(
"Couldn't establish connection for SplunkHECAppender named \""
+ this.getName() + "\".");
}
final byte[] bytes = getLayout().toByteArray(event);
String formatted = new String(bytes);
shi.streamEvent(formatted);
} catch (Exception ex) {
if (!ignoreExceptions()) {
throw new AppenderLoggingException(ex);
}
} finally {
readLock.unlock();
}
}
@PluginFactory
public static SplunkHECAppender createAppender(
@PluginAttribute("name") String name,
@PluginElement("Layout") Layout<? extends Serializable> layout,
@PluginElement("Filter") final Filter filter,
@PluginAttribute("token") String token,
@PluginAttribute("host") String host,
@PluginAttribute("port") int port,
@PluginAttribute("poolsize") int poolsize,
@PluginAttribute("https") boolean https,
@PluginAttribute("index") String index,
@PluginAttribute("source") String source,
@PluginAttribute("sourcetype") String sourcetype,
@PluginAttribute("maxQueueSize") String maxQueueSize,
@PluginAttribute("dropEventsOnQueueFull") boolean dropEventsOnQueueFull,
@PluginAttribute("batchMode") boolean batchMode,
@PluginAttribute("maxBatchSizeBytes") String maxBatchSizeBytes,
@PluginAttribute("maxBatchSizeEvents") long maxBatchSizeEvents,
@PluginAttribute("maxInactiveTimeBeforeBatchFlush") long maxInactiveTimeBeforeBatchFlush) {
if (name == null) {
LOGGER.error("No name provided for SplunkHECAppender");
return null;
}
if (layout == null) {
layout = PatternLayout.createDefaultLayout();
}
HECTransportConfig config = new HECTransportConfig();
if (token == null) {
LOGGER.error("No token provided for SplunkHECAppender");
return null;
}
config.setHost(host);
config.setPort(port);
config.setToken(token);
config.setPoolsize(poolsize);
config.setHttps(https);
config.setIndex(index);
config.setSource(source);
config.setSourcetype(sourcetype);
config.setBatchMode(batchMode);
config.setMaxBatchSizeBytes(maxBatchSizeBytes);
config.setMaxBatchSizeEvents(maxBatchSizeEvents);
config.setMaxInactiveTimeBeforeBatchFlush(maxInactiveTimeBeforeBatchFlush);
return new SplunkHECAppender(name, config, dropEventsOnQueueFull,
maxQueueSize, filter, layout, true);
}
} | package com.splunk.logging.log4j2.appender;
import java.io.Serializable;
import java.util.concurrent.locks.*;
import IMPORT_0.apache.logging.log4j.core.layout.PatternLayout;
import IMPORT_0.apache.logging.log4j.core.*;
import IMPORT_0.apache.logging.log4j.core.appender.AbstractAppender;
import IMPORT_0.apache.logging.log4j.core.appender.AppenderLoggingException;
import IMPORT_0.apache.logging.log4j.core.config.plugins.*;
import com.splunk.logging.HECTransportConfig;
import com.splunk.logging.SplunkHECInput;
@VAR_0(name = "SplunkHECAppender", category = "Core", elementType = "appender", printObject = true)
public final class SplunkHECAppender extends AbstractAppender {
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Lock readLock = rwLock.readLock();
// connection settings
private HECTransportConfig config;
// queuing settings
private String maxQueueSize;
private boolean dropEventsOnQueueFull;
private SplunkHECInput shi;
protected SplunkHECAppender(String name, HECTransportConfig config,
boolean dropEventsOnQueueFull, String maxQueueSize, Filter filter,
Layout<? extends Serializable> layout,
final boolean ignoreExceptions) {
super(name, filter, layout, ignoreExceptions);
this.config = config;
try {
this.shi = new SplunkHECInput(config);
this.shi.setMaxQueueSize(maxQueueSize);
this.shi.setDropEventsOnQueueFull(dropEventsOnQueueFull);
} catch (Exception e) {
}
}
@Override
public void append(LogEvent event) {
readLock.lock();
try {
try {
if (shi == null) {
shi = new SplunkHECInput(config);
shi.setMaxQueueSize(maxQueueSize);
shi.setDropEventsOnQueueFull(dropEventsOnQueueFull);
}
} catch (Exception e) {
throw new AppenderLoggingException(
"Couldn't establish connection for SplunkHECAppender named \""
+ this.getName() + "\".");
}
final byte[] bytes = getLayout().toByteArray(event);
String formatted = new String(bytes);
shi.streamEvent(formatted);
} catch (Exception ex) {
if (!ignoreExceptions()) {
throw new AppenderLoggingException(ex);
}
} finally {
readLock.unlock();
}
}
@PluginFactory
public static SplunkHECAppender createAppender(
@PluginAttribute("name") String name,
@PluginElement("Layout") Layout<? extends Serializable> layout,
@PluginElement("Filter") final Filter filter,
@PluginAttribute("token") String token,
@PluginAttribute("host") String host,
@PluginAttribute("port") int port,
@PluginAttribute("poolsize") int poolsize,
@PluginAttribute("https") boolean https,
@PluginAttribute("index") String index,
@PluginAttribute("source") String source,
@PluginAttribute("sourcetype") String sourcetype,
@PluginAttribute("maxQueueSize") String maxQueueSize,
@PluginAttribute("dropEventsOnQueueFull") boolean dropEventsOnQueueFull,
@PluginAttribute("batchMode") boolean batchMode,
@PluginAttribute("maxBatchSizeBytes") String maxBatchSizeBytes,
@PluginAttribute("maxBatchSizeEvents") long maxBatchSizeEvents,
@PluginAttribute("maxInactiveTimeBeforeBatchFlush") long maxInactiveTimeBeforeBatchFlush) {
if (name == null) {
LOGGER.error("No name provided for SplunkHECAppender");
return null;
}
if (layout == null) {
layout = PatternLayout.createDefaultLayout();
}
HECTransportConfig config = new HECTransportConfig();
if (token == null) {
LOGGER.error("No token provided for SplunkHECAppender");
return null;
}
config.setHost(host);
config.setPort(port);
config.setToken(token);
config.setPoolsize(poolsize);
config.setHttps(https);
config.FUNC_0(index);
config.setSource(source);
config.setSourcetype(sourcetype);
config.setBatchMode(batchMode);
config.setMaxBatchSizeBytes(maxBatchSizeBytes);
config.setMaxBatchSizeEvents(maxBatchSizeEvents);
config.setMaxInactiveTimeBeforeBatchFlush(maxInactiveTimeBeforeBatchFlush);
return new SplunkHECAppender(name, config, dropEventsOnQueueFull,
maxQueueSize, filter, layout, true);
}
} | 0.074297 | {'IMPORT_0': 'org', 'VAR_0': 'Plugin', 'FUNC_0': 'setIndex'} | java | Hibrido | 52.55% |
package com.scj.beilu.app.mvp.course.bean;
import com.scj.beilu.app.mvp.common.bean.FormatTimeBean;
import java.util.List;
/**
* @author Mingxun
* @time on 2019/3/25 17:28
*/
public class CourseCommentInfoBean extends FormatTimeBean {
/**
* courseCommentId : 6
* courseId : 21
* userId : 72
* userName : 明巡
* userHead : http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLknksDZvB81soMRxgNYEicAyL8w0SKrm7zgHwpz4S3iaNnHBYUib685d4k0BUAicsyHemaROGPL8IU5Q/132
* userHeadCompression : http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLknksDZvB81soMRxgNYEicAyL8w0SKrm7zgHwpz4S3iaNnHBYUib685d4k0BUAicsyHemaROGPL8IU5Q/132
* comContent : 理解理解
* comDate : 2019-03-25 20:26:06
* replies : []
*/
private int courseCommentId;
private int courseId;
private int userId;
private String userName;
private String userHead;
private String userHeadCompression;
private String comContent;
private String comDate;
private List<?> replies;
public int getCourseCommentId() {
return courseCommentId;
}
public void setCourseCommentId(int courseCommentId) {
this.courseCommentId = courseCommentId;
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserHead() {
return userHead;
}
public void setUserHead(String userHead) {
this.userHead = userHead;
}
public String getUserHeadCompression() {
return userHeadCompression;
}
public void setUserHeadCompression(String userHeadCompression) {
this.userHeadCompression = userHeadCompression;
}
public String getComContent() {
return comContent;
}
public void setComContent(String comContent) {
this.comContent = comContent;
}
public String getComDate() {
return comDate;
}
public void setComDate(String comDate) {
this.comDate = comDate;
}
public List<?> getReplies() {
return replies;
}
public void setReplies(List<?> replies) {
this.replies = replies;
}
@Override
public String getFormatDate() {
return getComDate();
}
}
| package com.scj.beilu.IMPORT_0.mvp.course.bean;
import com.scj.beilu.IMPORT_0.mvp.common.bean.FormatTimeBean;
import java.util.IMPORT_1;
/**
* @author Mingxun
* @time on 2019/3/25 17:28
*/
public class CLASS_0 extends FormatTimeBean {
/**
* courseCommentId : 6
* courseId : 21
* userId : 72
* userName : 明巡
* userHead : http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLknksDZvB81soMRxgNYEicAyL8w0SKrm7zgHwpz4S3iaNnHBYUib685d4k0BUAicsyHemaROGPL8IU5Q/132
* userHeadCompression : http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLknksDZvB81soMRxgNYEicAyL8w0SKrm7zgHwpz4S3iaNnHBYUib685d4k0BUAicsyHemaROGPL8IU5Q/132
* comContent : 理解理解
* comDate : 2019-03-25 20:26:06
* replies : []
*/
private int courseCommentId;
private int courseId;
private int userId;
private CLASS_1 VAR_0;
private CLASS_1 userHead;
private CLASS_1 VAR_1;
private CLASS_1 VAR_2;
private CLASS_1 comDate;
private IMPORT_1<?> replies;
public int getCourseCommentId() {
return courseCommentId;
}
public void setCourseCommentId(int courseCommentId) {
this.courseCommentId = courseCommentId;
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public int getUserId() {
return userId;
}
public void FUNC_0(int userId) {
this.userId = userId;
}
public CLASS_1 getUserName() {
return VAR_0;
}
public void setUserName(CLASS_1 VAR_0) {
this.VAR_0 = VAR_0;
}
public CLASS_1 FUNC_1() {
return userHead;
}
public void FUNC_2(CLASS_1 userHead) {
this.userHead = userHead;
}
public CLASS_1 getUserHeadCompression() {
return VAR_1;
}
public void FUNC_3(CLASS_1 VAR_1) {
this.VAR_1 = VAR_1;
}
public CLASS_1 getComContent() {
return VAR_2;
}
public void FUNC_4(CLASS_1 VAR_2) {
this.VAR_2 = VAR_2;
}
public CLASS_1 getComDate() {
return comDate;
}
public void FUNC_5(CLASS_1 comDate) {
this.comDate = comDate;
}
public IMPORT_1<?> FUNC_6() {
return replies;
}
public void setReplies(IMPORT_1<?> replies) {
this.replies = replies;
}
@Override
public CLASS_1 FUNC_7() {
return getComDate();
}
}
| 0.396838 | {'IMPORT_0': 'app', 'IMPORT_1': 'List', 'CLASS_0': 'CourseCommentInfoBean', 'CLASS_1': 'String', 'VAR_0': 'userName', 'VAR_1': 'userHeadCompression', 'VAR_2': 'comContent', 'FUNC_0': 'setUserId', 'FUNC_1': 'getUserHead', 'FUNC_2': 'setUserHead', 'FUNC_3': 'setUserHeadCompression', 'FUNC_4': 'setComContent', 'FUNC_5': 'setComDate', 'FUNC_6': 'getReplies', 'FUNC_7': 'getFormatDate'} | java | OOP | 100.00% |
/**
* Contact the offsite service and fetch the uptime ratios.
*/
public void refresh() {
if (this.monitorApiKey.length() == 0) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("https://api.uptimerobot.com/getMonitors?apiKey=");
sb.append(this.monitorApiKey);
sb.append("&customUptimeRatio=1-7-30-365");
String url = sb.toString();
byte[] xml = loadPageWithRetries(url);
Match doc;
try {
doc = $(new ByteArrayInputStream(xml));
} catch (SAXException | IOException e) {
throw new CouldNotRefresh(e);
}
String[] customRatios = doc.find("monitor").attr("customuptimeratio").split("-");
this.last24HoursUptimeRatio = customRatios[0];
this.last7DaysUptimeRatio = customRatios[1];
this.last30DaysUptimeRatio = customRatios[2];
this.last365DaysUptimeRatio = customRatios[3];
} | /**
* Contact the offsite service and fetch the uptime ratios.
*/
public void FUNC_0() {
if (this.monitorApiKey.length() == 0) {
return;
}
CLASS_0 sb = new CLASS_0();
sb.append("https://api.uptimerobot.com/getMonitors?apiKey=");
sb.append(this.monitorApiKey);
sb.append("&customUptimeRatio=1-7-30-365");
CLASS_1 url = sb.FUNC_1();
byte[] VAR_0 = FUNC_2(url);
CLASS_2 VAR_1;
try {
VAR_1 = $(new CLASS_3(VAR_0));
} catch (SAXException | IOException e) {
throw new CouldNotRefresh(e);
}
CLASS_1[] VAR_2 = VAR_1.find("monitor").FUNC_3("customuptimeratio").split("-");
this.VAR_3 = VAR_2[0];
this.VAR_4 = VAR_2[1];
this.last30DaysUptimeRatio = VAR_2[2];
this.VAR_5 = VAR_2[3];
} | 0.477662 | {'FUNC_0': 'refresh', 'CLASS_0': 'StringBuilder', 'CLASS_1': 'String', 'FUNC_1': 'toString', 'VAR_0': 'xml', 'FUNC_2': 'loadPageWithRetries', 'CLASS_2': 'Match', 'VAR_1': 'doc', 'CLASS_3': 'ByteArrayInputStream', 'VAR_2': 'customRatios', 'FUNC_3': 'attr', 'VAR_3': 'last24HoursUptimeRatio', 'VAR_4': 'last7DaysUptimeRatio', 'VAR_5': 'last365DaysUptimeRatio'} | java | Procedural | 19.09% |
/**
* The method to register a new user.
*
* @param firstName First name of the user.
* @param lastName Last name of the user.
* @param email Email address of the user.
* @param userName User name for the user. This will be used to login to the server.
* @param password The password for the user.
* @param confirmPassword Password confirmation.
* @return After the user is created it navigates back to the login page.
* @throws IOException
*/
public LoginPage registerUser(String firstName, String lastName, String email, String userName, String password,
String confirmPassword) throws IOException {
handleAction(firstName, lastName, email, userName, password, confirmPassword);
return new LoginPage(driver);
} | /**
* The method to register a new user.
*
* @param firstName First name of the user.
* @param lastName Last name of the user.
* @param email Email address of the user.
* @param userName User name for the user. This will be used to login to the server.
* @param password The password for the user.
* @param confirmPassword Password confirmation.
* @return After the user is created it navigates back to the login page.
* @throws IOException
*/
public CLASS_0 FUNC_0(CLASS_1 VAR_0, CLASS_1 VAR_1, CLASS_1 VAR_2, CLASS_1 VAR_3, CLASS_1 VAR_4,
CLASS_1 VAR_5) throws CLASS_2 {
FUNC_1(VAR_0, VAR_1, VAR_2, VAR_3, VAR_4, VAR_5);
return new CLASS_0(VAR_6);
} | 0.931343 | {'CLASS_0': 'LoginPage', 'FUNC_0': 'registerUser', 'CLASS_1': 'String', 'VAR_0': 'firstName', 'VAR_1': 'lastName', 'VAR_2': 'email', 'VAR_3': 'userName', 'VAR_4': 'password', 'VAR_5': 'confirmPassword', 'CLASS_2': 'IOException', 'FUNC_1': 'handleAction', 'VAR_6': 'driver'} | java | Procedural | 84.91% |
package com.crescentflare.unilayoutexample.nestedlayouts;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.crescentflare.unilayoutexample.R;
/**
* The nested layouts activity loads a layout file with nested UniLayout containers
*/
public class NestedLayoutsActivity extends AppCompatActivity
{
// ---
// Initialization
// ---
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nested_layouts);
setTitle(getString(R.string.example_nested_layouts));
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
}
// ---
// Menu handling
// ---
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home)
{
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| package com.crescentflare.unilayoutexample.nestedlayouts;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.crescentflare.unilayoutexample.R;
/**
* The nested layouts activity loads a layout file with nested UniLayout containers
*/
public class NestedLayoutsActivity extends AppCompatActivity
{
// ---
// Initialization
// ---
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nested_layouts);
setTitle(getString(R.string.example_nested_layouts));
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
}
// ---
// Menu handling
// ---
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.VAR_0)
{
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 0.047961 | {'VAR_0': 'home'} | java | OOP | 52.90% |
/**
* Update some criteria at once
*
* @param queryId Query identifier
* @return Service data
* @throws AWException Query failed
*/
private ServiceData updateModel(String queryId) throws AWException {
ServiceData serviceData = launchQuery(queryId);
List<String> columnList = DataListUtil.getColumnList(serviceData.getDataList());
for (String column : columnList) {
if (!AweConstants.JSON_ID_PARAMETER.equals(column)) {
ClientAction clientAction = new ClientAction("select");
clientAction.addParameter("values", new CellData(DataListUtil.getColumn(serviceData.getDataList(), column)));
clientAction.setTarget(column);
clientAction.setAsync(Boolean.TRUE);
serviceData.addClientAction(clientAction);
}
}
return serviceData;
} | /**
* Update some criteria at once
*
* @param queryId Query identifier
* @return Service data
* @throws AWException Query failed
*/
private CLASS_0 updateModel(String VAR_0) throws AWException {
CLASS_0 VAR_1 = FUNC_0(VAR_0);
List<String> columnList = DataListUtil.getColumnList(VAR_1.getDataList());
for (String column : columnList) {
if (!VAR_2.VAR_3.FUNC_1(column)) {
CLASS_1 clientAction = new CLASS_1("select");
clientAction.addParameter("values", new CellData(DataListUtil.getColumn(VAR_1.getDataList(), column)));
clientAction.setTarget(column);
clientAction.setAsync(VAR_4.TRUE);
VAR_1.FUNC_2(clientAction);
}
}
return VAR_1;
} | 0.38368 | {'CLASS_0': 'ServiceData', 'VAR_0': 'queryId', 'VAR_1': 'serviceData', 'FUNC_0': 'launchQuery', 'VAR_2': 'AweConstants', 'VAR_3': 'JSON_ID_PARAMETER', 'FUNC_1': 'equals', 'CLASS_1': 'ClientAction', 'VAR_4': 'Boolean', 'FUNC_2': 'addClientAction'} | java | Procedural | 25.00% |
package doctorgallus.kerdos;
import java.util.Map;
import java.util.TreeMap;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.config.Config;
import net.minecraftforge.common.config.Config.Comment;
import net.minecraftforge.common.config.ConfigManager;
import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import doctorgallus.kerdos.Kerdos;
@Config(modid = Kerdos.MODID, category = "")
public class KerdosConfig
{
public static final GeneralConfig general = new GeneralConfig();
public static class GeneralConfig
{
@Comment({"Initial funds players start with."})
@Config.RangeInt(min = 0)
public int startingFunds = 0;
@Comment({"Minimum percentage of funds to be released on payout."})
@Config.RangeDouble(min = 0D, max = 1D)
public double payoutRateMin = 0.3D;
@Comment({"Maximum percentage of funds to be released on payout."})
@Config.RangeDouble(min = 0D, max = 1D)
public double payoutRateMax = 0.5D;
@Comment({
"Currency items used for payout.",
"Syntax: modid:itemname@value",
"Syntax: modid:itemname:meta@value",
"where \"value\" is the monetary value of that item.",
"When omitting \"meta\" it defaults to \"0\"."
})
@Config.RequiresWorldRestart
public String[] currencyItems = {
"jjcoin:copper_coin@1",
"jjcoin:silver_coin@10",
"jjcoin:gold_coin@100",
"jjcoin:diamond_coin@1000"
};
@Comment({"Loot tables to use for payout."})
@Config.RequiresWorldRestart
public String[] payoutLootTables = {
"minecraft:chests/abandoned_mineshaft",
"minecraft:chests/desert_pyramid",
"minecraft:chests/end_city_treasure",
"minecraft:chests/igloo_chest",
"minecraft:chests/jungle_temple",
"minecraft:chests/nether_bridge",
"minecraft:chests/simple_dungeon",
"minecraft:chests/stronghold_corridor",
"minecraft:chests/stronghold_crossing",
"minecraft:chests/stronghold_library",
"minecraft:chests/village_blacksmith",
"minecraft:chests/woodland_mansion",
"minecraft:entities/evocation_illager",
"minecraft:entities/giant",
"minecraft:entities/husk",
"minecraft:entities/skeleton",
"minecraft:entities/stray",
"minecraft:entities/villager",
"minecraft:entities/vindication_illager",
"minecraft:entities/witch",
"minecraft:entities/wither_skeleton",
"minecraft:entities/zombie",
"minecraft:entities/zombie_pigman",
"minecraft:entities/zombie_villager"
};
@Comment({
"Blocks which increase your fund when harvested.",
"Syntax: modid:itemname@value",
"Syntax: modid:itemname:meta@value",
"where \"value\" is the value by which a players fund should be increased.",
"When omitting \"meta\" it defaults to \"0\".",
"A \"*\" can be used to match all possible \"meta\" values."
})
public String[] fundSourceBlocks = {
"minecraft:diamond_ore@10",
"minecraft:emerald_block@5",
"biomesoplenty:gem_ore:*@5"
};
@Comment({
"If enabled, Fortune enchantments also apply to fund increases when harvesting a block.",
"Uses the formula `base_value * (1 / (fortune_lvl + 2) + (fortune_lvl + 1) / 2)` which corresponds to the average drops increase for ores in vanilla minecraft."
})
public boolean applyFortuneEnchantment = true;
}
@EventBusSubscriber(modid = Kerdos.MODID)
public static class Handler
{
public static TreeMap<Integer, ItemStack> currencyItems = new TreeMap();
@SubscribeEvent
public static void onConfigChangedEvent(OnConfigChangedEvent event)
{
if (event.getModID().equals(Kerdos.MODID))
{
ConfigManager.sync(Kerdos.MODID, Config.Type.INSTANCE);
reloadConfig();
}
}
public static void reloadConfig()
{
KerdosEventHandler.payoutLootPools = null;
KerdosConfig.Handler.currencyItems.clear();
for (String entry : KerdosConfig.general.currencyItems)
{
String[] data = entry.split("@");
String[] name = data[0].split(":");
if (name.length >= 2)
{
Item item = Item.getByNameOrId(name[0] + ":" + name[1]);
if (item != null)
{
ItemStack stack = item.getDefaultInstance();
if (name.length == 3)
{
int meta;
try
{
meta = Integer.parseInt(name[2]);
}
catch (NumberFormatException e)
{
continue;
}
stack.setItemDamage(meta);
}
int value;
try
{
value = Integer.parseInt(data[1]);
}
catch (NumberFormatException e)
{
continue;
}
KerdosConfig.Handler.currencyItems.put(value, stack);
}
}
}
}
}
}
| package IMPORT_0.IMPORT_1;
import IMPORT_2.IMPORT_3.Map;
import IMPORT_2.IMPORT_3.IMPORT_4;
import IMPORT_5.IMPORT_6.IMPORT_7.IMPORT_8;
import IMPORT_5.IMPORT_6.IMPORT_7.ItemStack;
import IMPORT_5.minecraftforge.IMPORT_9.IMPORT_10.IMPORT_11;
import IMPORT_5.minecraftforge.IMPORT_9.IMPORT_10.IMPORT_11.IMPORT_12;
import IMPORT_5.minecraftforge.IMPORT_9.IMPORT_10.IMPORT_13;
import IMPORT_5.minecraftforge.IMPORT_14.IMPORT_15.IMPORT_16.IMPORT_17.IMPORT_18;
import IMPORT_5.minecraftforge.IMPORT_14.IMPORT_9.IMPORT_19.SubscribeEvent;
import IMPORT_5.minecraftforge.IMPORT_14.IMPORT_9.Mod.EventBusSubscriber;
import IMPORT_0.IMPORT_1.IMPORT_20;
@IMPORT_11(VAR_0 = IMPORT_20.MODID, VAR_1 = "")
public class CLASS_0
{
public static final CLASS_1 VAR_3 = new CLASS_1();
public static class CLASS_1
{
@IMPORT_12({"Initial funds players start with."})
@IMPORT_11.IMPORT_21(VAR_4 = 0)
public int VAR_5 = 0;
@IMPORT_12({"Minimum percentage of funds to be released on payout."})
@IMPORT_11.IMPORT_22(VAR_4 = 0D, VAR_6 = 1D)
public double VAR_7 = 0.3D;
@IMPORT_12({"Maximum percentage of funds to be released on payout."})
@IMPORT_11.IMPORT_22(VAR_4 = 0D, VAR_6 = 1D)
public double VAR_8 = 0.5D;
@IMPORT_12({
"Currency items used for payout.",
"Syntax: modid:itemname@value",
"Syntax: modid:itemname:meta@value",
"where \"value\" is the monetary value of that item.",
"When omitting \"meta\" it defaults to \"0\"."
})
@IMPORT_11.IMPORT_23
public CLASS_2[] VAR_9 = {
"jjcoin:copper_coin@1",
"jjcoin:silver_coin@10",
"jjcoin:gold_coin@100",
"jjcoin:diamond_coin@1000"
};
@IMPORT_12({"Loot tables to use for payout."})
@IMPORT_11.IMPORT_23
public CLASS_2[] VAR_10 = {
"minecraft:chests/abandoned_mineshaft",
"minecraft:chests/desert_pyramid",
"minecraft:chests/end_city_treasure",
"minecraft:chests/igloo_chest",
"minecraft:chests/jungle_temple",
"minecraft:chests/nether_bridge",
"minecraft:chests/simple_dungeon",
"minecraft:chests/stronghold_corridor",
"minecraft:chests/stronghold_crossing",
"minecraft:chests/stronghold_library",
"minecraft:chests/village_blacksmith",
"minecraft:chests/woodland_mansion",
"minecraft:entities/evocation_illager",
"minecraft:entities/giant",
"minecraft:entities/husk",
"minecraft:entities/skeleton",
"minecraft:entities/stray",
"minecraft:entities/villager",
"minecraft:entities/vindication_illager",
"minecraft:entities/witch",
"minecraft:entities/wither_skeleton",
"minecraft:entities/zombie",
"minecraft:entities/zombie_pigman",
"minecraft:entities/zombie_villager"
};
@IMPORT_12({
"Blocks which increase your fund when harvested.",
"Syntax: modid:itemname@value",
"Syntax: modid:itemname:meta@value",
"where \"value\" is the value by which a players fund should be increased.",
"When omitting \"meta\" it defaults to \"0\".",
"A \"*\" can be used to match all possible \"meta\" values."
})
public CLASS_2[] VAR_11 = {
"minecraft:diamond_ore@10",
"minecraft:emerald_block@5",
"biomesoplenty:gem_ore:*@5"
};
@IMPORT_12({
"If enabled, Fortune enchantments also apply to fund increases when harvesting a block.",
"Uses the formula `base_value * (1 / (fortune_lvl + 2) + (fortune_lvl + 1) / 2)` which corresponds to the average drops increase for ores in vanilla minecraft."
})
public boolean VAR_12 = true;
}
@EventBusSubscriber(VAR_0 = IMPORT_20.MODID)
public static class CLASS_3
{
public static IMPORT_4<CLASS_4, ItemStack> VAR_9 = new IMPORT_4();
@SubscribeEvent
public static void FUNC_0(IMPORT_18 IMPORT_16)
{
if (IMPORT_16.FUNC_1().FUNC_2(IMPORT_20.MODID))
{
IMPORT_13.FUNC_3(IMPORT_20.MODID, IMPORT_11.VAR_15.VAR_16);
FUNC_4();
}
}
public static void FUNC_4()
{
VAR_17.payoutLootPools = null;
VAR_2.VAR_13.VAR_9.clear();
for (CLASS_2 VAR_18 : VAR_2.VAR_3.VAR_9)
{
CLASS_2[] VAR_19 = VAR_18.FUNC_5("@");
CLASS_2[] VAR_20 = VAR_19[0].FUNC_5(":");
if (VAR_20.VAR_21 >= 2)
{
IMPORT_8 IMPORT_7 = IMPORT_8.FUNC_6(VAR_20[0] + ":" + VAR_20[1]);
if (IMPORT_7 != null)
{
ItemStack VAR_22 = IMPORT_7.FUNC_7();
if (VAR_20.VAR_21 == 3)
{
int VAR_23;
try
{
VAR_23 = VAR_14.FUNC_8(VAR_20[2]);
}
catch (NumberFormatException e)
{
continue;
}
VAR_22.FUNC_9(VAR_23);
}
int VAR_24;
try
{
VAR_24 = VAR_14.FUNC_8(VAR_19[1]);
}
catch (NumberFormatException e)
{
continue;
}
VAR_2.VAR_13.VAR_9.FUNC_10(VAR_24, VAR_22);
}
}
}
}
}
}
| 0.818601 | {'IMPORT_0': 'doctorgallus', 'IMPORT_1': 'kerdos', 'IMPORT_2': 'java', 'IMPORT_3': 'util', 'IMPORT_4': 'TreeMap', 'IMPORT_5': 'net', 'IMPORT_6': 'minecraft', 'IMPORT_7': 'item', 'IMPORT_8': 'Item', 'IMPORT_9': 'common', 'IMPORT_10': 'config', 'IMPORT_11': 'Config', 'IMPORT_12': 'Comment', 'IMPORT_13': 'ConfigManager', 'IMPORT_14': 'fml', 'IMPORT_15': 'client', 'IMPORT_16': 'event', 'IMPORT_17': 'ConfigChangedEvent', 'IMPORT_18': 'OnConfigChangedEvent', 'IMPORT_19': 'eventhandler', 'IMPORT_20': 'Kerdos', 'VAR_0': 'modid', 'VAR_1': 'category', 'CLASS_0': 'KerdosConfig', 'VAR_2': 'KerdosConfig', 'CLASS_1': 'GeneralConfig', 'VAR_3': 'general', 'IMPORT_21': 'RangeInt', 'VAR_4': 'min', 'VAR_5': 'startingFunds', 'IMPORT_22': 'RangeDouble', 'VAR_6': 'max', 'VAR_7': 'payoutRateMin', 'VAR_8': 'payoutRateMax', 'IMPORT_23': 'RequiresWorldRestart', 'CLASS_2': 'String', 'VAR_9': 'currencyItems', 'VAR_10': 'payoutLootTables', 'VAR_11': 'fundSourceBlocks', 'VAR_12': 'applyFortuneEnchantment', 'CLASS_3': 'Handler', 'VAR_13': 'Handler', 'CLASS_4': 'Integer', 'VAR_14': 'Integer', 'FUNC_0': 'onConfigChangedEvent', 'FUNC_1': 'getModID', 'FUNC_2': 'equals', 'FUNC_3': 'sync', 'VAR_15': 'Type', 'VAR_16': 'INSTANCE', 'FUNC_4': 'reloadConfig', 'VAR_17': 'KerdosEventHandler', 'VAR_18': 'entry', 'VAR_19': 'data', 'FUNC_5': 'split', 'VAR_20': 'name', 'VAR_21': 'length', 'FUNC_6': 'getByNameOrId', 'VAR_22': 'stack', 'FUNC_7': 'getDefaultInstance', 'VAR_23': 'meta', 'FUNC_8': 'parseInt', 'FUNC_9': 'setItemDamage', 'VAR_24': 'value', 'FUNC_10': 'put'} | java | error | 0 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.dlp.v2.model;
/**
* Pseudonymization method that generates deterministic encryption for the given input. Outputs a
* base64 encoded representation of the encrypted output. Uses AES-SIV based on the RFC
* https://tools.ietf.org/html/rfc5297.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Data Loss Prevention (DLP) API. For a detailed
* explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GooglePrivacyDlpV2CryptoDeterministicConfig extends com.google.api.client.json.GenericJson {
/**
* A context may be used for higher security and maintaining referential integrity such that the
* same identifier in two different contexts will be given a distinct surrogate. The context is
* appended to plaintext value being encrypted. On decryption the provided context is validated
* against the value used during encryption. If a context was provided during encryption, same
* context must be provided during decryption as well.
*
* If the context is not set, plaintext would be used as is for encryption. If the context is set
* but:
*
* 1. there is no record present when transforming a given value or 2. the field is not present
* when transforming a given value,
*
* plaintext would be used as is for encryption.
*
* Note that case (1) is expected when an `InfoTypeTransformation` is applied to both structured
* and non-structured `ContentItem`s.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GooglePrivacyDlpV2FieldId context;
/**
* The key used by the encryption function.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GooglePrivacyDlpV2CryptoKey cryptoKey;
/**
* The custom info type to annotate the surrogate with. This annotation will be applied to the
* surrogate by prefixing it with the name of the custom info type followed by the number of
* characters comprising the surrogate. The following scheme defines the format: {info type
* name}({surrogate character count}):{surrogate}
*
* For example, if the name of custom info type is 'MY_TOKEN_INFO_TYPE' and the surrogate is
* 'abc', the full replacement value will be: 'MY_TOKEN_INFO_TYPE(3):abc'
*
* This annotation identifies the surrogate when inspecting content using the custom info type
* 'Surrogate'. This facilitates reversal of the surrogate when it occurs in free text.
*
* Note: For record transformations where the entire cell in a table is being transformed,
* surrogates are not mandatory. Surrogates are used to denote the location of the token and are
* necessary for re-identification in free form text.
*
* In order for inspection to work properly, the name of this info type must not occur naturally
* anywhere in your data; otherwise, inspection may either
*
* - reverse a surrogate that does not correspond to an actual identifier - be unable to parse the
* surrogate and result in an error
*
* Therefore, choose your custom info type name carefully after considering what your data looks
* like. One way to select a name that has a high chance of yielding reliable detection is to
* include one or more unicode characters that are highly improbable to exist in your data. For
* example, assuming your data is entered from a regular ASCII keyboard, the symbol with the hex
* code point 29DD might be used like so: ⧝MY_TOKEN_TYPE.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GooglePrivacyDlpV2InfoType surrogateInfoType;
/**
* A context may be used for higher security and maintaining referential integrity such that the
* same identifier in two different contexts will be given a distinct surrogate. The context is
* appended to plaintext value being encrypted. On decryption the provided context is validated
* against the value used during encryption. If a context was provided during encryption, same
* context must be provided during decryption as well.
*
* If the context is not set, plaintext would be used as is for encryption. If the context is set
* but:
*
* 1. there is no record present when transforming a given value or 2. the field is not present
* when transforming a given value,
*
* plaintext would be used as is for encryption.
*
* Note that case (1) is expected when an `InfoTypeTransformation` is applied to both structured
* and non-structured `ContentItem`s.
* @return value or {@code null} for none
*/
public GooglePrivacyDlpV2FieldId getContext() {
return context;
}
/**
* A context may be used for higher security and maintaining referential integrity such that the
* same identifier in two different contexts will be given a distinct surrogate. The context is
* appended to plaintext value being encrypted. On decryption the provided context is validated
* against the value used during encryption. If a context was provided during encryption, same
* context must be provided during decryption as well.
*
* If the context is not set, plaintext would be used as is for encryption. If the context is set
* but:
*
* 1. there is no record present when transforming a given value or 2. the field is not present
* when transforming a given value,
*
* plaintext would be used as is for encryption.
*
* Note that case (1) is expected when an `InfoTypeTransformation` is applied to both structured
* and non-structured `ContentItem`s.
* @param context context or {@code null} for none
*/
public GooglePrivacyDlpV2CryptoDeterministicConfig setContext(GooglePrivacyDlpV2FieldId context) {
this.context = context;
return this;
}
/**
* The key used by the encryption function.
* @return value or {@code null} for none
*/
public GooglePrivacyDlpV2CryptoKey getCryptoKey() {
return cryptoKey;
}
/**
* The key used by the encryption function.
* @param cryptoKey cryptoKey or {@code null} for none
*/
public GooglePrivacyDlpV2CryptoDeterministicConfig setCryptoKey(GooglePrivacyDlpV2CryptoKey cryptoKey) {
this.cryptoKey = cryptoKey;
return this;
}
/**
* The custom info type to annotate the surrogate with. This annotation will be applied to the
* surrogate by prefixing it with the name of the custom info type followed by the number of
* characters comprising the surrogate. The following scheme defines the format: {info type
* name}({surrogate character count}):{surrogate}
*
* For example, if the name of custom info type is 'MY_TOKEN_INFO_TYPE' and the surrogate is
* 'abc', the full replacement value will be: 'MY_TOKEN_INFO_TYPE(3):abc'
*
* This annotation identifies the surrogate when inspecting content using the custom info type
* 'Surrogate'. This facilitates reversal of the surrogate when it occurs in free text.
*
* Note: For record transformations where the entire cell in a table is being transformed,
* surrogates are not mandatory. Surrogates are used to denote the location of the token and are
* necessary for re-identification in free form text.
*
* In order for inspection to work properly, the name of this info type must not occur naturally
* anywhere in your data; otherwise, inspection may either
*
* - reverse a surrogate that does not correspond to an actual identifier - be unable to parse the
* surrogate and result in an error
*
* Therefore, choose your custom info type name carefully after considering what your data looks
* like. One way to select a name that has a high chance of yielding reliable detection is to
* include one or more unicode characters that are highly improbable to exist in your data. For
* example, assuming your data is entered from a regular ASCII keyboard, the symbol with the hex
* code point 29DD might be used like so: ⧝MY_TOKEN_TYPE.
* @return value or {@code null} for none
*/
public GooglePrivacyDlpV2InfoType getSurrogateInfoType() {
return surrogateInfoType;
}
/**
* The custom info type to annotate the surrogate with. This annotation will be applied to the
* surrogate by prefixing it with the name of the custom info type followed by the number of
* characters comprising the surrogate. The following scheme defines the format: {info type
* name}({surrogate character count}):{surrogate}
*
* For example, if the name of custom info type is 'MY_TOKEN_INFO_TYPE' and the surrogate is
* 'abc', the full replacement value will be: 'MY_TOKEN_INFO_TYPE(3):abc'
*
* This annotation identifies the surrogate when inspecting content using the custom info type
* 'Surrogate'. This facilitates reversal of the surrogate when it occurs in free text.
*
* Note: For record transformations where the entire cell in a table is being transformed,
* surrogates are not mandatory. Surrogates are used to denote the location of the token and are
* necessary for re-identification in free form text.
*
* In order for inspection to work properly, the name of this info type must not occur naturally
* anywhere in your data; otherwise, inspection may either
*
* - reverse a surrogate that does not correspond to an actual identifier - be unable to parse the
* surrogate and result in an error
*
* Therefore, choose your custom info type name carefully after considering what your data looks
* like. One way to select a name that has a high chance of yielding reliable detection is to
* include one or more unicode characters that are highly improbable to exist in your data. For
* example, assuming your data is entered from a regular ASCII keyboard, the symbol with the hex
* code point 29DD might be used like so: ⧝MY_TOKEN_TYPE.
* @param surrogateInfoType surrogateInfoType or {@code null} for none
*/
public GooglePrivacyDlpV2CryptoDeterministicConfig setSurrogateInfoType(GooglePrivacyDlpV2InfoType surrogateInfoType) {
this.surrogateInfoType = surrogateInfoType;
return this;
}
@Override
public GooglePrivacyDlpV2CryptoDeterministicConfig set(String fieldName, Object value) {
return (GooglePrivacyDlpV2CryptoDeterministicConfig) super.set(fieldName, value);
}
@Override
public GooglePrivacyDlpV2CryptoDeterministicConfig clone() {
return (GooglePrivacyDlpV2CryptoDeterministicConfig) super.clone();
}
}
| /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.v2.model;
/**
* Pseudonymization method that generates deterministic encryption for the given input. Outputs a
* base64 encoded representation of the encrypted output. Uses AES-SIV based on the RFC
* https://tools.ietf.org/html/rfc5297.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Data Loss Prevention (DLP) API. For a detailed
* explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GooglePrivacyDlpV2CryptoDeterministicConfig extends IMPORT_0.IMPORT_1.IMPORT_2.CLASS_0.CLASS_1.CLASS_2 {
/**
* A context may be used for higher security and maintaining referential integrity such that the
* same identifier in two different contexts will be given a distinct surrogate. The context is
* appended to plaintext value being encrypted. On decryption the provided context is validated
* against the value used during encryption. If a context was provided during encryption, same
* context must be provided during decryption as well.
*
* If the context is not set, plaintext would be used as is for encryption. If the context is set
* but:
*
* 1. there is no record present when transforming a given value or 2. the field is not present
* when transforming a given value,
*
* plaintext would be used as is for encryption.
*
* Note that case (1) is expected when an `InfoTypeTransformation` is applied to both structured
* and non-structured `ContentItem`s.
* The value may be {@code null}.
*/
@IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_5.IMPORT_6.IMPORT_7
private CLASS_3 VAR_0;
/**
* The key used by the encryption function.
* The value may be {@code null}.
*/
@IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_5.IMPORT_6.IMPORT_7
private CLASS_4 VAR_1;
/**
* The custom info type to annotate the surrogate with. This annotation will be applied to the
* surrogate by prefixing it with the name of the custom info type followed by the number of
* characters comprising the surrogate. The following scheme defines the format: {info type
* name}({surrogate character count}):{surrogate}
*
* For example, if the name of custom info type is 'MY_TOKEN_INFO_TYPE' and the surrogate is
* 'abc', the full replacement value will be: 'MY_TOKEN_INFO_TYPE(3):abc'
*
* This annotation identifies the surrogate when inspecting content using the custom info type
* 'Surrogate'. This facilitates reversal of the surrogate when it occurs in free text.
*
* Note: For record transformations where the entire cell in a table is being transformed,
* surrogates are not mandatory. Surrogates are used to denote the location of the token and are
* necessary for re-identification in free form text.
*
* In order for inspection to work properly, the name of this info type must not occur naturally
* anywhere in your data; otherwise, inspection may either
*
* - reverse a surrogate that does not correspond to an actual identifier - be unable to parse the
* surrogate and result in an error
*
* Therefore, choose your custom info type name carefully after considering what your data looks
* like. One way to select a name that has a high chance of yielding reliable detection is to
* include one or more unicode characters that are highly improbable to exist in your data. For
* example, assuming your data is entered from a regular ASCII keyboard, the symbol with the hex
* code point 29DD might be used like so: ⧝MY_TOKEN_TYPE.
* The value may be {@code null}.
*/
@IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_5.IMPORT_6.IMPORT_7
private CLASS_5 VAR_2;
/**
* A context may be used for higher security and maintaining referential integrity such that the
* same identifier in two different contexts will be given a distinct surrogate. The context is
* appended to plaintext value being encrypted. On decryption the provided context is validated
* against the value used during encryption. If a context was provided during encryption, same
* context must be provided during decryption as well.
*
* If the context is not set, plaintext would be used as is for encryption. If the context is set
* but:
*
* 1. there is no record present when transforming a given value or 2. the field is not present
* when transforming a given value,
*
* plaintext would be used as is for encryption.
*
* Note that case (1) is expected when an `InfoTypeTransformation` is applied to both structured
* and non-structured `ContentItem`s.
* @return value or {@code null} for none
*/
public CLASS_3 FUNC_0() {
return VAR_0;
}
/**
* A context may be used for higher security and maintaining referential integrity such that the
* same identifier in two different contexts will be given a distinct surrogate. The context is
* appended to plaintext value being encrypted. On decryption the provided context is validated
* against the value used during encryption. If a context was provided during encryption, same
* context must be provided during decryption as well.
*
* If the context is not set, plaintext would be used as is for encryption. If the context is set
* but:
*
* 1. there is no record present when transforming a given value or 2. the field is not present
* when transforming a given value,
*
* plaintext would be used as is for encryption.
*
* Note that case (1) is expected when an `InfoTypeTransformation` is applied to both structured
* and non-structured `ContentItem`s.
* @param context context or {@code null} for none
*/
public GooglePrivacyDlpV2CryptoDeterministicConfig FUNC_1(CLASS_3 VAR_0) {
this.VAR_0 = VAR_0;
return this;
}
/**
* The key used by the encryption function.
* @return value or {@code null} for none
*/
public CLASS_4 FUNC_2() {
return VAR_1;
}
/**
* The key used by the encryption function.
* @param cryptoKey cryptoKey or {@code null} for none
*/
public GooglePrivacyDlpV2CryptoDeterministicConfig FUNC_3(CLASS_4 VAR_1) {
this.VAR_1 = VAR_1;
return this;
}
/**
* The custom info type to annotate the surrogate with. This annotation will be applied to the
* surrogate by prefixing it with the name of the custom info type followed by the number of
* characters comprising the surrogate. The following scheme defines the format: {info type
* name}({surrogate character count}):{surrogate}
*
* For example, if the name of custom info type is 'MY_TOKEN_INFO_TYPE' and the surrogate is
* 'abc', the full replacement value will be: 'MY_TOKEN_INFO_TYPE(3):abc'
*
* This annotation identifies the surrogate when inspecting content using the custom info type
* 'Surrogate'. This facilitates reversal of the surrogate when it occurs in free text.
*
* Note: For record transformations where the entire cell in a table is being transformed,
* surrogates are not mandatory. Surrogates are used to denote the location of the token and are
* necessary for re-identification in free form text.
*
* In order for inspection to work properly, the name of this info type must not occur naturally
* anywhere in your data; otherwise, inspection may either
*
* - reverse a surrogate that does not correspond to an actual identifier - be unable to parse the
* surrogate and result in an error
*
* Therefore, choose your custom info type name carefully after considering what your data looks
* like. One way to select a name that has a high chance of yielding reliable detection is to
* include one or more unicode characters that are highly improbable to exist in your data. For
* example, assuming your data is entered from a regular ASCII keyboard, the symbol with the hex
* code point 29DD might be used like so: ⧝MY_TOKEN_TYPE.
* @return value or {@code null} for none
*/
public CLASS_5 FUNC_4() {
return VAR_2;
}
/**
* The custom info type to annotate the surrogate with. This annotation will be applied to the
* surrogate by prefixing it with the name of the custom info type followed by the number of
* characters comprising the surrogate. The following scheme defines the format: {info type
* name}({surrogate character count}):{surrogate}
*
* For example, if the name of custom info type is 'MY_TOKEN_INFO_TYPE' and the surrogate is
* 'abc', the full replacement value will be: 'MY_TOKEN_INFO_TYPE(3):abc'
*
* This annotation identifies the surrogate when inspecting content using the custom info type
* 'Surrogate'. This facilitates reversal of the surrogate when it occurs in free text.
*
* Note: For record transformations where the entire cell in a table is being transformed,
* surrogates are not mandatory. Surrogates are used to denote the location of the token and are
* necessary for re-identification in free form text.
*
* In order for inspection to work properly, the name of this info type must not occur naturally
* anywhere in your data; otherwise, inspection may either
*
* - reverse a surrogate that does not correspond to an actual identifier - be unable to parse the
* surrogate and result in an error
*
* Therefore, choose your custom info type name carefully after considering what your data looks
* like. One way to select a name that has a high chance of yielding reliable detection is to
* include one or more unicode characters that are highly improbable to exist in your data. For
* example, assuming your data is entered from a regular ASCII keyboard, the symbol with the hex
* code point 29DD might be used like so: ⧝MY_TOKEN_TYPE.
* @param surrogateInfoType surrogateInfoType or {@code null} for none
*/
public GooglePrivacyDlpV2CryptoDeterministicConfig FUNC_5(CLASS_5 VAR_2) {
this.VAR_2 = VAR_2;
return this;
}
@VAR_3
public GooglePrivacyDlpV2CryptoDeterministicConfig FUNC_6(CLASS_6 fieldName, Object VAR_4) {
return (GooglePrivacyDlpV2CryptoDeterministicConfig) super.FUNC_6(fieldName, VAR_4);
}
@VAR_3
public GooglePrivacyDlpV2CryptoDeterministicConfig FUNC_7() {
return (GooglePrivacyDlpV2CryptoDeterministicConfig) super.FUNC_7();
}
}
| 0.88323 | {'IMPORT_0': 'com', 'IMPORT_1': 'google', 'IMPORT_2': 'api', 'IMPORT_3': 'services', 'IMPORT_4': 'dlp', 'CLASS_0': 'client', 'IMPORT_5': 'client', 'CLASS_1': 'json', 'CLASS_2': 'GenericJson', 'IMPORT_6': 'util', 'IMPORT_7': 'Key', 'CLASS_3': 'GooglePrivacyDlpV2FieldId', 'VAR_0': 'context', 'CLASS_4': 'GooglePrivacyDlpV2CryptoKey', 'VAR_1': 'cryptoKey', 'CLASS_5': 'GooglePrivacyDlpV2InfoType', 'VAR_2': 'surrogateInfoType', 'FUNC_0': 'getContext', 'FUNC_1': 'setContext', 'FUNC_2': 'getCryptoKey', 'FUNC_3': 'setCryptoKey', 'FUNC_4': 'getSurrogateInfoType', 'FUNC_5': 'setSurrogateInfoType', 'VAR_3': 'Override', 'FUNC_6': 'set', 'CLASS_6': 'String', 'VAR_4': 'value', 'FUNC_7': 'clone'} | java | Hibrido | 26.49% |
package org.example.lotty.domain.activity.service.deploy;
import org.example.lotty.domain.activity.model.aggregates.ActivityInfoLimitPageRich;
import org.example.lotty.domain.activity.model.req.ActivityConfigReq;
import org.example.lotty.domain.activity.model.req.ActivityInfoLimitPageReq;
import org.example.lotty.domain.activity.model.vo.ActivityVO;
import java.util.List;
/**
* 部署活动配置接口
*/
public interface IActivityDeploy {
/**
* 创建活动信息
*
* @param req 活动配置信息
*/
void createActivity(ActivityConfigReq req);
/**
* 修改活动信息
*
* @param req 活动配置信息
*/
void updateActivity(ActivityConfigReq req);
/**
* 扫描待处理的活动列表,状态为:通过、活动中
* <p>
* 通过 -> 时间符合时 -> 活动中
* 活动中 -> 时间到期时 -> 关闭
*
* @param id ID
* @return 待处理的活动集合
*/
List<ActivityVO> scanToDoActivityList(Long id);
/**
* 查询活动分页查询聚合对象
*
* @param req 请求参数;分页、活动
* @return 查询结果
*/
ActivityInfoLimitPageRich queryActivityInfoLimitPage(ActivityInfoLimitPageReq req);
}
| package org.example.lotty.IMPORT_0.activity.service.deploy;
import org.example.lotty.IMPORT_0.activity.model.IMPORT_1.ActivityInfoLimitPageRich;
import org.example.lotty.IMPORT_0.activity.model.req.ActivityConfigReq;
import org.example.lotty.IMPORT_0.activity.model.req.ActivityInfoLimitPageReq;
import org.example.lotty.IMPORT_0.activity.model.vo.ActivityVO;
import java.util.List;
/**
* 部署活动配置接口
*/
public interface IActivityDeploy {
/**
* 创建活动信息
*
* @param req 活动配置信息
*/
void createActivity(ActivityConfigReq req);
/**
* 修改活动信息
*
* @param req 活动配置信息
*/
void FUNC_0(ActivityConfigReq req);
/**
* 扫描待处理的活动列表,状态为:通过、活动中
* <p>
* 通过 -> 时间符合时 -> 活动中
* 活动中 -> 时间到期时 -> 关闭
*
* @param id ID
* @return 待处理的活动集合
*/
List<ActivityVO> scanToDoActivityList(Long id);
/**
* 查询活动分页查询聚合对象
*
* @param req 请求参数;分页、活动
* @return 查询结果
*/
ActivityInfoLimitPageRich queryActivityInfoLimitPage(ActivityInfoLimitPageReq req);
}
| 0.236763 | {'IMPORT_0': 'domain', 'IMPORT_1': 'aggregates', 'FUNC_0': 'updateActivity'} | java | Texto | 57.78% |
import java.io.*;
import java.util.*;
public class MaximumMedian{
static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
public static int[] arr;
public static int n;
public static int k;
public static void main(String[] args) throws IOException {
StringTokenizer st = new StringTokenizer(r.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
arr = new int[n];
st = new StringTokenizer(r.readLine());
for (int i = 0; i < n; i ++)
arr[i] = Integer.parseInt(st.nextToken());
Arrays.sort(arr);
pw.println(solve());
pw.close();
}
public static long solve() {
long low = 0; long high = Integer.MAX_VALUE;
while (low < high) {
long middle = (low + high + 1) / 2;
long operationsRequired = findOperations(middle);
if (operationsRequired <= k)
low = middle;
else
high = middle - 1;
}
return low;
}
public static long findOperations(long x) {
long counter = 0;
for (int i = n / 2; i < n; i ++)
counter += Math.max(0, x - arr[i]);
return counter;
}
} | import java.io.*;
import java.util.*;
public class MaximumMedian{
static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
public static int[] arr;
public static int n;
public static int k;
public static void main(String[] args) throws IOException {
StringTokenizer st = new StringTokenizer(r.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
arr = new int[n];
st = new StringTokenizer(r.readLine());
for (int i = 0; i < n; i ++)
arr[i] = Integer.parseInt(st.nextToken());
Arrays.sort(arr);
pw.println(solve());
pw.close();
}
public static long solve() {
long low = 0; long high = Integer.VAR_0;
while (low < high) {
long middle = (low + high + 1) / 2;
long operationsRequired = findOperations(middle);
if (operationsRequired <= k)
low = middle;
else
high = middle - 1;
}
return low;
}
public static long findOperations(long x) {
long counter = 0;
for (int i = n / 2; i < n; i ++)
counter += Math.max(0, x - arr[i]);
return counter;
}
} | 0.045076 | {'VAR_0': 'MAX_VALUE'} | java | OOP | 9.13% |
package com.github.crizin.webs.exception;
public class WebsRequestException extends WebsException {
public WebsRequestException(Throwable cause) {
super(cause);
}
public WebsRequestException(String message) {
super(message);
}
public WebsRequestException(String message, Throwable cause) {
super(message, cause);
}
} | package com.github.crizin.webs.exception;
public class WebsRequestException extends WebsException {
public WebsRequestException(Throwable VAR_0) {
super(VAR_0);
}
public WebsRequestException(String message) {
super(message);
}
public WebsRequestException(String message, Throwable VAR_0) {
super(message, VAR_0);
}
} | 0.280031 | {'VAR_0': 'cause'} | java | OOP | 100.00% |
//funcion que pasa el textview de la frase a voz
private void hablar() {
String text = frase.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} | //funcion que pasa el textview de la frase a voz
private void FUNC_0() {
CLASS_0 VAR_0 = frase.getText().toString();
VAR_1.FUNC_1(VAR_0, TextToSpeech.QUEUE_FLUSH, null);
} | 0.496084 | {'FUNC_0': 'hablar', 'CLASS_0': 'String', 'VAR_0': 'text', 'VAR_1': 'tts', 'FUNC_1': 'speak'} | java | Procedural | 100.00% |
/**
* Returns an entry holding this attribute as the key and the actual request value as the value.
*/
static Entry<HttpRequestAttribute<?>, Object> entry(final int position, final HttpRequest request) {
if (position >= VALUES.length) {
throw new NoSuchElementException();
}
final HttpRequestAttributes<?> key = VALUES[position];
return Maps.entry(key, key.parameterValue(request).get());
} | /**
* Returns an entry holding this attribute as the key and the actual request value as the value.
*/
static CLASS_0<CLASS_1<?>, CLASS_2> FUNC_0(final int VAR_0, final CLASS_3 VAR_1) {
if (VAR_0 >= VAR_2.VAR_3) {
throw new NoSuchElementException();
}
final CLASS_4<?> VAR_4 = VAR_2[VAR_0];
return VAR_5.FUNC_0(VAR_4, VAR_4.FUNC_1(VAR_1).FUNC_2());
} | 0.951464 | {'CLASS_0': 'Entry', 'CLASS_1': 'HttpRequestAttribute', 'CLASS_2': 'Object', 'FUNC_0': 'entry', 'VAR_0': 'position', 'CLASS_3': 'HttpRequest', 'VAR_1': 'request', 'VAR_2': 'VALUES', 'VAR_3': 'length', 'CLASS_4': 'HttpRequestAttributes', 'VAR_4': 'key', 'VAR_5': 'Maps', 'FUNC_1': 'parameterValue', 'FUNC_2': 'get'} | java | Procedural | 89.06% |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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 io.siddhi.extension.execution.time;
import io.siddhi.annotation.Example;
import io.siddhi.annotation.Extension;
import io.siddhi.annotation.Parameter;
import io.siddhi.annotation.ParameterOverload;
import io.siddhi.annotation.ReturnAttribute;
import io.siddhi.annotation.util.DataType;
import io.siddhi.core.config.SiddhiQueryContext;
import io.siddhi.core.exception.SiddhiAppRuntimeException;
import io.siddhi.core.executor.ConstantExpressionExecutor;
import io.siddhi.core.executor.ExpressionExecutor;
import io.siddhi.core.executor.function.FunctionExecutor;
import io.siddhi.core.util.config.ConfigReader;
import io.siddhi.core.util.snapshot.state.State;
import io.siddhi.core.util.snapshot.state.StateFactory;
import io.siddhi.extension.execution.time.util.TimeExtensionConstants;
import io.siddhi.query.api.definition.Attribute;
import io.siddhi.query.api.exception.SiddhiAppValidationException;
import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* extract(unit,dateValue,dateFormat)/extract(unit,dateValue,dateFormat,locale)/extract(unit,dateValue)
* /extract(timestampInMilliseconds,unit)/extract(timestampInMilliseconds,unit,locale)
* Returns date attributes from a date expression.
* dateValue - value of date. eg: "2014-11-11 13:23:44.657", "2014-11-11" , "13:23:44.657"
* unit - Which part of the date format you want to manipulate. eg: "MINUTE" , "HOUR" , "MONTH" , "YEAR" , "QUARTER" ,
* "WEEK" , "DAY" , "SECOND"
* dateFormat - Date format of the provided date value. eg: yyyy-MM-dd HH:mm:ss.SSS
* timestampInMilliseconds - date value in milliseconds.(from the epoch) eg: 1415712224000L
* locale - optional parameter which represents a specific geographical, political or cultural region.
* eg: "en_US", "fr_FR"
* Accept Type(s) for extract(unit,dateValue,dateFormat):
* unit : STRING
* dateValue : STRING
* dateFormat : STRING
* Accept Type(s) for extract(timestampInMilliseconds,unit):
* timestampInMilliseconds : LONG
* unit : STRING
* Return Type(s): INT
*/
/**
* Class representing the Time extract implementation.
*/
@Extension(
name = "extract",
namespace = "time",
description = "Function extracts a date unit from the date.",
parameters = {
@Parameter(name = "unit",
description = "This is the part of the date that needs to be modified. " +
"For example, `MINUTE`, `HOUR`, `MONTH`, `YEAR`, `QUARTER`," +
" `WEEK`, `DAY`, `SECOND`.",
type = {DataType.STRING}),
@Parameter(name = "date.value",
description = "The value of the date. " +
"For example, `2014-11-11 13:23:44.657`, `2014-11-11`, " +
"`13:23:44.657`.",
type = {DataType.STRING},
dynamic = true,
optional = true,
defaultValue = "-"),
@Parameter(name = "date.format",
description = "The format of the date value provided. " +
"For example, `yyyy-MM-dd HH:mm:ss.SSS`.",
type = {DataType.STRING},
dynamic = true,
optional = true,
defaultValue = "`yyyy-MM-dd HH:mm:ss.SSS`"),
@Parameter(name = "timestamp.in.milliseconds",
description = "The date value in milliseconds. For example, `1415712224000L`.",
type = {DataType.LONG},
dynamic = true,
optional = true,
defaultValue = "-"),
@Parameter(name = "locale",
description = "Represents a specific geographical, political or cultural region. " +
"For example `en_US` and `fr_FR`",
type = {DataType.STRING},
optional = true,
defaultValue = "Current default locale set in the Java Virtual Machine.")
},
parameterOverloads = {
@ParameterOverload(parameterNames = {"unit", "date.value"}),
@ParameterOverload(parameterNames = {"unit", "date.value", "date.format"}),
@ParameterOverload(parameterNames = {"unit", "date.value", "date.format", "locale"}),
@ParameterOverload(parameterNames = {"timestamp.in.milliseconds", "unit"}),
@ParameterOverload(parameterNames = {"timestamp.in.milliseconds", "unit", "locale"})
},
returnAttributes = @ReturnAttribute(
description = "Returns the extracted data unit value.",
type = {DataType.INT}),
examples = {
@Example(
syntax = "time:extract('YEAR', '2019/11/11 13:23:44.657', 'yyyy/MM/dd HH:mm:ss.SSS')",
description = "Extracts the year amount and returns `2019`."
),
@Example(
syntax = "time:extract('DAY', '2019-11-12 13:23:44.657')",
description = "Extracts the day amount and returns `12`."
),
@Example(
syntax = "time:extract(1394556804000L, 'HOUR')",
description = "Extracts the hour amount and returns `22`."
)
}
)
public class ExtractAttributesFunctionExtension extends FunctionExecutor {
private Attribute.Type returnType = Attribute.Type.INT;
private boolean useDefaultDateFormat = false;
private String dateFormat = null;
private Calendar cal = Calendar.getInstance();
private String unit = null;
private boolean isLocaleDefined = false;
private boolean useTimestampInMilliseconds = false;
private Locale locale = null;
@Override
protected StateFactory init(ExpressionExecutor[] attributeExpressionExecutors,
ConfigReader configReader, SiddhiQueryContext siddhiQueryContext) {
if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.LONG && attributeExpressionExecutors
.length == 2) {
useDefaultDateFormat = true;
dateFormat = TimeExtensionConstants.EXTENSION_TIME_DEFAULT_DATE_FORMAT;
}
if (attributeExpressionExecutors.length == 4) {
locale = LocaleUtils.toLocale((String) ((ConstantExpressionExecutor)
attributeExpressionExecutors[3]).getValue());
unit = ((String) ((ConstantExpressionExecutor) attributeExpressionExecutors[0])
.getValue()).toUpperCase(Locale.getDefault());
} else if (attributeExpressionExecutors.length == 3) {
if (attributeExpressionExecutors[0].getReturnType() == Attribute.Type.LONG) {
useTimestampInMilliseconds = true;
locale = LocaleUtils.toLocale((String) ((ConstantExpressionExecutor)
attributeExpressionExecutors[2]).getValue());
unit = ((String) ((ConstantExpressionExecutor) attributeExpressionExecutors[1]).getValue()).
toUpperCase(Locale.getDefault());
} else {
unit = ((String) ((ConstantExpressionExecutor) attributeExpressionExecutors[0]).getValue()).
toUpperCase(Locale.getDefault());
}
} else if (attributeExpressionExecutors.length == 2) {
if (useDefaultDateFormat) {
unit = ((String) ((ConstantExpressionExecutor) attributeExpressionExecutors[0]).getValue()).
toUpperCase(Locale.getDefault());
} else {
unit = ((String) ((ConstantExpressionExecutor) attributeExpressionExecutors[1]).getValue()).
toUpperCase(Locale.getDefault());
}
} else {
throw new SiddhiAppValidationException("Invalid no of arguments passed to time:extract() function, " +
"required 2 or 3, but found " +
attributeExpressionExecutors.length);
}
if (locale != null) {
isLocaleDefined = true;
cal = Calendar.getInstance(locale);
} else {
cal = Calendar.getInstance();
}
return null;
}
@Override
protected Object execute(Object[] data, State state) {
String source = null;
if ((data.length == 3 || data.length == 4 || useDefaultDateFormat) && !useTimestampInMilliseconds) {
try {
if (data[1] == null) {
if (isLocaleDefined) {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(unit,dateValue," +
"dateFormat, locale) function" + ". Second " +
"argument cannot be null");
} else {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(unit,dateValue," +
"dateFormat) function" + ". Second " +
"argument cannot be null");
}
}
if (!useDefaultDateFormat) {
if (data[2] == null) {
if (isLocaleDefined) {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(unit,dateValue," +
"dateFormat, locale) function" + ". Third " +
"argument cannot be null");
} else {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(unit,dateValue," +
"dateFormat) function" + ". Third " +
"argument cannot be null");
}
}
dateFormat = (String) data[2];
}
FastDateFormat userSpecificFormat;
source = (String) data[1];
userSpecificFormat = FastDateFormat.getInstance(dateFormat);
Date userSpecifiedDate = userSpecificFormat.parse(source);
cal.setTime(userSpecifiedDate);
} catch (ParseException e) {
String errorMsg = "Provided format " + dateFormat + " does not match with the timestamp " + source +
". " + e.getMessage();
throw new SiddhiAppRuntimeException(errorMsg, e);
} catch (ClassCastException e) {
String errorMsg = "Provided Data type cannot be cast to desired format. " + e.getMessage();
throw new SiddhiAppRuntimeException(errorMsg, e);
}
} else {
if (data[0] == null) {
if (isLocaleDefined) {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(timestampInMilliseconds," +
"unit, locale) function" + ". First " + "argument cannot be null");
} else {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(timestampInMilliseconds," +
"unit) function" + ". First " + "argument cannot be null");
}
}
try {
long millis = (Long) data[0];
cal.setTimeInMillis(millis);
} catch (ClassCastException e) {
String errorMsg = "Provided Data type cannot be cast to desired format. " + e.getMessage();
throw new SiddhiAppRuntimeException(errorMsg, e);
}
}
int returnValue = 0;
if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_YEAR)) {
returnValue = cal.get(Calendar.YEAR);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_MONTH)) {
returnValue = (cal.get(Calendar.MONTH) + 1);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_SECOND)) {
returnValue = cal.get(Calendar.SECOND);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_MINUTE)) {
returnValue = cal.get(Calendar.MINUTE);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_HOUR)) {
returnValue = cal.get(Calendar.HOUR_OF_DAY);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_DAY)) {
returnValue = cal.get(Calendar.DAY_OF_MONTH);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_WEEK)) {
returnValue = cal.get(Calendar.WEEK_OF_YEAR);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_QUARTER)) {
returnValue = (cal.get(Calendar.MONTH) / 3) + 1;
}
return returnValue;
}
@Override
protected Object execute(Object data, State state) {
return null;
}
@Override
public Attribute.Type getReturnType() {
return returnType;
}
}
| /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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 IMPORT_0.IMPORT_1.IMPORT_2.execution.time;
import IMPORT_0.IMPORT_1.IMPORT_3.IMPORT_4;
import IMPORT_0.IMPORT_1.IMPORT_3.IMPORT_5;
import IMPORT_0.IMPORT_1.IMPORT_3.IMPORT_6;
import IMPORT_0.IMPORT_1.IMPORT_3.IMPORT_7;
import IMPORT_0.IMPORT_1.IMPORT_3.ReturnAttribute;
import IMPORT_0.IMPORT_1.IMPORT_3.IMPORT_8.IMPORT_9;
import IMPORT_0.IMPORT_1.IMPORT_10.IMPORT_11.SiddhiQueryContext;
import IMPORT_0.IMPORT_1.IMPORT_10.IMPORT_12.IMPORT_13;
import IMPORT_0.IMPORT_1.IMPORT_10.IMPORT_14.IMPORT_15;
import IMPORT_0.IMPORT_1.IMPORT_10.IMPORT_14.ExpressionExecutor;
import IMPORT_0.IMPORT_1.IMPORT_10.IMPORT_14.IMPORT_16.IMPORT_17;
import IMPORT_0.IMPORT_1.IMPORT_10.IMPORT_8.IMPORT_11.ConfigReader;
import IMPORT_0.IMPORT_1.IMPORT_10.IMPORT_8.IMPORT_18.state.IMPORT_19;
import IMPORT_0.IMPORT_1.IMPORT_10.IMPORT_8.IMPORT_18.state.IMPORT_20;
import IMPORT_0.IMPORT_1.IMPORT_2.execution.time.IMPORT_8.IMPORT_21;
import IMPORT_0.IMPORT_1.IMPORT_22.IMPORT_23.definition.IMPORT_24;
import IMPORT_0.IMPORT_1.IMPORT_22.IMPORT_23.IMPORT_12.SiddhiAppValidationException;
import IMPORT_25.IMPORT_26.commons.IMPORT_27.LocaleUtils;
import IMPORT_25.IMPORT_26.commons.IMPORT_27.time.IMPORT_28;
import IMPORT_29.text.IMPORT_30;
import IMPORT_29.IMPORT_8.IMPORT_31;
import IMPORT_29.IMPORT_8.IMPORT_32;
import IMPORT_29.IMPORT_8.IMPORT_33;
/**
* extract(unit,dateValue,dateFormat)/extract(unit,dateValue,dateFormat,locale)/extract(unit,dateValue)
* /extract(timestampInMilliseconds,unit)/extract(timestampInMilliseconds,unit,locale)
* Returns date attributes from a date expression.
* dateValue - value of date. eg: "2014-11-11 13:23:44.657", "2014-11-11" , "13:23:44.657"
* unit - Which part of the date format you want to manipulate. eg: "MINUTE" , "HOUR" , "MONTH" , "YEAR" , "QUARTER" ,
* "WEEK" , "DAY" , "SECOND"
* dateFormat - Date format of the provided date value. eg: yyyy-MM-dd HH:mm:ss.SSS
* timestampInMilliseconds - date value in milliseconds.(from the epoch) eg: 1415712224000L
* locale - optional parameter which represents a specific geographical, political or cultural region.
* eg: "en_US", "fr_FR"
* Accept Type(s) for extract(unit,dateValue,dateFormat):
* unit : STRING
* dateValue : STRING
* dateFormat : STRING
* Accept Type(s) for extract(timestampInMilliseconds,unit):
* timestampInMilliseconds : LONG
* unit : STRING
* Return Type(s): INT
*/
/**
* Class representing the Time extract implementation.
*/
@IMPORT_5(
VAR_0 = "extract",
namespace = "time",
VAR_1 = "Function extracts a date unit from the date.",
VAR_2 = {
@IMPORT_6(VAR_0 = "unit",
VAR_1 = "This is the part of the date that needs to be modified. " +
"For example, `MINUTE`, `HOUR`, `MONTH`, `YEAR`, `QUARTER`," +
" `WEEK`, `DAY`, `SECOND`.",
type = {IMPORT_9.STRING}),
@IMPORT_6(VAR_0 = "date.value",
VAR_1 = "The value of the date. " +
"For example, `2014-11-11 13:23:44.657`, `2014-11-11`, " +
"`13:23:44.657`.",
type = {IMPORT_9.STRING},
VAR_3 = true,
optional = true,
VAR_4 = "-"),
@IMPORT_6(VAR_0 = "date.format",
VAR_1 = "The format of the date value provided. " +
"For example, `yyyy-MM-dd HH:mm:ss.SSS`.",
type = {IMPORT_9.STRING},
VAR_3 = true,
optional = true,
VAR_4 = "`yyyy-MM-dd HH:mm:ss.SSS`"),
@IMPORT_6(VAR_0 = "timestamp.in.milliseconds",
VAR_1 = "The date value in milliseconds. For example, `1415712224000L`.",
type = {IMPORT_9.VAR_5},
VAR_3 = true,
optional = true,
VAR_4 = "-"),
@IMPORT_6(VAR_0 = "locale",
VAR_1 = "Represents a specific geographical, political or cultural region. " +
"For example `en_US` and `fr_FR`",
type = {IMPORT_9.STRING},
optional = true,
VAR_4 = "Current default locale set in the Java Virtual Machine.")
},
VAR_6 = {
@IMPORT_7(VAR_7 = {"unit", "date.value"}),
@IMPORT_7(VAR_7 = {"unit", "date.value", "date.format"}),
@IMPORT_7(VAR_7 = {"unit", "date.value", "date.format", "locale"}),
@IMPORT_7(VAR_7 = {"timestamp.in.milliseconds", "unit"}),
@IMPORT_7(VAR_7 = {"timestamp.in.milliseconds", "unit", "locale"})
},
VAR_8 = @ReturnAttribute(
VAR_1 = "Returns the extracted data unit value.",
type = {IMPORT_9.VAR_9}),
VAR_10 = {
@IMPORT_4(
VAR_11 = "time:extract('YEAR', '2019/11/11 13:23:44.657', 'yyyy/MM/dd HH:mm:ss.SSS')",
VAR_1 = "Extracts the year amount and returns `2019`."
),
@IMPORT_4(
VAR_11 = "time:extract('DAY', '2019-11-12 13:23:44.657')",
VAR_1 = "Extracts the day amount and returns `12`."
),
@IMPORT_4(
VAR_11 = "time:extract(1394556804000L, 'HOUR')",
VAR_1 = "Extracts the hour amount and returns `22`."
)
}
)
public class CLASS_0 extends IMPORT_17 {
private IMPORT_24.CLASS_1 VAR_13 = IMPORT_24.VAR_12.VAR_9;
private boolean useDefaultDateFormat = false;
private CLASS_2 VAR_14 = null;
private IMPORT_31 cal = IMPORT_31.FUNC_0();
private CLASS_2 VAR_15 = null;
private boolean VAR_16 = false;
private boolean useTimestampInMilliseconds = false;
private IMPORT_33 VAR_17 = null;
@VAR_18
protected IMPORT_20 FUNC_1(ExpressionExecutor[] VAR_19,
ConfigReader VAR_20, SiddhiQueryContext siddhiQueryContext) {
if (VAR_19[0].FUNC_2() != IMPORT_24.VAR_12.VAR_5 && VAR_19
.VAR_21 == 2) {
useDefaultDateFormat = true;
VAR_14 = IMPORT_21.VAR_22;
}
if (VAR_19.VAR_21 == 4) {
VAR_17 = LocaleUtils.FUNC_3((CLASS_2) ((IMPORT_15)
VAR_19[3]).FUNC_4());
VAR_15 = ((CLASS_2) ((IMPORT_15) VAR_19[0])
.FUNC_4()).toUpperCase(IMPORT_33.getDefault());
} else if (VAR_19.VAR_21 == 3) {
if (VAR_19[0].FUNC_2() == IMPORT_24.VAR_12.VAR_5) {
useTimestampInMilliseconds = true;
VAR_17 = LocaleUtils.FUNC_3((CLASS_2) ((IMPORT_15)
VAR_19[2]).FUNC_4());
VAR_15 = ((CLASS_2) ((IMPORT_15) VAR_19[1]).FUNC_4()).
toUpperCase(IMPORT_33.getDefault());
} else {
VAR_15 = ((CLASS_2) ((IMPORT_15) VAR_19[0]).FUNC_4()).
toUpperCase(IMPORT_33.getDefault());
}
} else if (VAR_19.VAR_21 == 2) {
if (useDefaultDateFormat) {
VAR_15 = ((CLASS_2) ((IMPORT_15) VAR_19[0]).FUNC_4()).
toUpperCase(IMPORT_33.getDefault());
} else {
VAR_15 = ((CLASS_2) ((IMPORT_15) VAR_19[1]).FUNC_4()).
toUpperCase(IMPORT_33.getDefault());
}
} else {
throw new SiddhiAppValidationException("Invalid no of arguments passed to time:extract() function, " +
"required 2 or 3, but found " +
VAR_19.VAR_21);
}
if (VAR_17 != null) {
VAR_16 = true;
cal = IMPORT_31.FUNC_0(VAR_17);
} else {
cal = IMPORT_31.FUNC_0();
}
return null;
}
@VAR_18
protected CLASS_3 FUNC_5(CLASS_3[] VAR_23, IMPORT_19 state) {
CLASS_2 source = null;
if ((VAR_23.VAR_21 == 3 || VAR_23.VAR_21 == 4 || useDefaultDateFormat) && !useTimestampInMilliseconds) {
try {
if (VAR_23[1] == null) {
if (VAR_16) {
throw new IMPORT_13("Invalid input given to time:extract(unit,dateValue," +
"dateFormat, locale) function" + ". Second " +
"argument cannot be null");
} else {
throw new IMPORT_13("Invalid input given to time:extract(unit,dateValue," +
"dateFormat) function" + ". Second " +
"argument cannot be null");
}
}
if (!useDefaultDateFormat) {
if (VAR_23[2] == null) {
if (VAR_16) {
throw new IMPORT_13("Invalid input given to time:extract(unit,dateValue," +
"dateFormat, locale) function" + ". Third " +
"argument cannot be null");
} else {
throw new IMPORT_13("Invalid input given to time:extract(unit,dateValue," +
"dateFormat) function" + ". Third " +
"argument cannot be null");
}
}
VAR_14 = (CLASS_2) VAR_23[2];
}
IMPORT_28 VAR_24;
source = (CLASS_2) VAR_23[1];
VAR_24 = IMPORT_28.FUNC_0(VAR_14);
IMPORT_32 userSpecifiedDate = VAR_24.FUNC_6(source);
cal.FUNC_7(userSpecifiedDate);
} catch (IMPORT_30 VAR_25) {
CLASS_2 errorMsg = "Provided format " + VAR_14 + " does not match with the timestamp " + source +
". " + VAR_25.getMessage();
throw new IMPORT_13(errorMsg, VAR_25);
} catch (CLASS_4 VAR_25) {
CLASS_2 errorMsg = "Provided Data type cannot be cast to desired format. " + VAR_25.getMessage();
throw new IMPORT_13(errorMsg, VAR_25);
}
} else {
if (VAR_23[0] == null) {
if (VAR_16) {
throw new IMPORT_13("Invalid input given to time:extract(timestampInMilliseconds," +
"unit, locale) function" + ". First " + "argument cannot be null");
} else {
throw new IMPORT_13("Invalid input given to time:extract(timestampInMilliseconds," +
"unit) function" + ". First " + "argument cannot be null");
}
}
try {
long millis = (Long) VAR_23[0];
cal.setTimeInMillis(millis);
} catch (CLASS_4 VAR_25) {
CLASS_2 errorMsg = "Provided Data type cannot be cast to desired format. " + VAR_25.getMessage();
throw new IMPORT_13(errorMsg, VAR_25);
}
}
int VAR_26 = 0;
if (VAR_15.FUNC_8(IMPORT_21.VAR_27)) {
VAR_26 = cal.get(IMPORT_31.VAR_28);
} else if (VAR_15.FUNC_8(IMPORT_21.VAR_29)) {
VAR_26 = (cal.get(IMPORT_31.VAR_30) + 1);
} else if (VAR_15.FUNC_8(IMPORT_21.VAR_31)) {
VAR_26 = cal.get(IMPORT_31.VAR_32);
} else if (VAR_15.FUNC_8(IMPORT_21.VAR_33)) {
VAR_26 = cal.get(IMPORT_31.VAR_34);
} else if (VAR_15.FUNC_8(IMPORT_21.VAR_35)) {
VAR_26 = cal.get(IMPORT_31.VAR_36);
} else if (VAR_15.FUNC_8(IMPORT_21.VAR_37)) {
VAR_26 = cal.get(IMPORT_31.VAR_38);
} else if (VAR_15.FUNC_8(IMPORT_21.VAR_39)) {
VAR_26 = cal.get(IMPORT_31.WEEK_OF_YEAR);
} else if (VAR_15.FUNC_8(IMPORT_21.EXTENSION_TIME_UNIT_QUARTER)) {
VAR_26 = (cal.get(IMPORT_31.VAR_30) / 3) + 1;
}
return VAR_26;
}
@VAR_18
protected CLASS_3 FUNC_5(CLASS_3 VAR_23, IMPORT_19 state) {
return null;
}
@VAR_18
public IMPORT_24.CLASS_1 FUNC_2() {
return VAR_13;
}
}
| 0.704096 | {'IMPORT_0': 'io', 'IMPORT_1': 'siddhi', 'IMPORT_2': 'extension', 'IMPORT_3': 'annotation', 'IMPORT_4': 'Example', 'IMPORT_5': 'Extension', 'IMPORT_6': 'Parameter', 'IMPORT_7': 'ParameterOverload', 'IMPORT_8': 'util', 'IMPORT_9': 'DataType', 'IMPORT_10': 'core', 'IMPORT_11': 'config', 'IMPORT_12': 'exception', 'IMPORT_13': 'SiddhiAppRuntimeException', 'IMPORT_14': 'executor', 'IMPORT_15': 'ConstantExpressionExecutor', 'IMPORT_16': 'function', 'IMPORT_17': 'FunctionExecutor', 'IMPORT_18': 'snapshot', 'IMPORT_19': 'State', 'IMPORT_20': 'StateFactory', 'IMPORT_21': 'TimeExtensionConstants', 'IMPORT_22': 'query', 'IMPORT_23': 'api', 'IMPORT_24': 'Attribute', 'IMPORT_25': 'org', 'IMPORT_26': 'apache', 'IMPORT_27': 'lang3', 'IMPORT_28': 'FastDateFormat', 'IMPORT_29': 'java', 'IMPORT_30': 'ParseException', 'IMPORT_31': 'Calendar', 'IMPORT_32': 'Date', 'IMPORT_33': 'Locale', 'VAR_0': 'name', 'VAR_1': 'description', 'VAR_2': 'parameters', 'VAR_3': 'dynamic', 'VAR_4': 'defaultValue', 'VAR_5': 'LONG', 'VAR_6': 'parameterOverloads', 'VAR_7': 'parameterNames', 'VAR_8': 'returnAttributes', 'VAR_9': 'INT', 'VAR_10': 'examples', 'VAR_11': 'syntax', 'CLASS_0': 'ExtractAttributesFunctionExtension', 'CLASS_1': 'Type', 'VAR_12': 'Type', 'VAR_13': 'returnType', 'CLASS_2': 'String', 'VAR_14': 'dateFormat', 'FUNC_0': 'getInstance', 'VAR_15': 'unit', 'VAR_16': 'isLocaleDefined', 'VAR_17': 'locale', 'VAR_18': 'Override', 'FUNC_1': 'init', 'VAR_19': 'attributeExpressionExecutors', 'VAR_20': 'configReader', 'FUNC_2': 'getReturnType', 'VAR_21': 'length', 'VAR_22': 'EXTENSION_TIME_DEFAULT_DATE_FORMAT', 'FUNC_3': 'toLocale', 'FUNC_4': 'getValue', 'CLASS_3': 'Object', 'FUNC_5': 'execute', 'VAR_23': 'data', 'VAR_24': 'userSpecificFormat', 'FUNC_6': 'parse', 'FUNC_7': 'setTime', 'VAR_25': 'e', 'CLASS_4': 'ClassCastException', 'VAR_26': 'returnValue', 'FUNC_8': 'equals', 'VAR_27': 'EXTENSION_TIME_UNIT_YEAR', 'VAR_28': 'YEAR', 'VAR_29': 'EXTENSION_TIME_UNIT_MONTH', 'VAR_30': 'MONTH', 'VAR_31': 'EXTENSION_TIME_UNIT_SECOND', 'VAR_32': 'SECOND', 'VAR_33': 'EXTENSION_TIME_UNIT_MINUTE', 'VAR_34': 'MINUTE', 'VAR_35': 'EXTENSION_TIME_UNIT_HOUR', 'VAR_36': 'HOUR_OF_DAY', 'VAR_37': 'EXTENSION_TIME_UNIT_DAY', 'VAR_38': 'DAY_OF_MONTH', 'VAR_39': 'EXTENSION_TIME_UNIT_WEEK'} | java | error | 0 |
/*
* MIT License
*
* Copyright (c) 2019-2020 jsnimda <<EMAIL>>
* Copyright (c) 2021-2022 <NAME>
*
* 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.anti_ad.mc.ipn.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation should be used by interested mods to inform Inventory Profiles Next(IPN)
* that one or more of their screens are not to be treated as inventories.
*
* <h2>What NOT to blacklist?</h2>
* <ul>
* <li>
* If your screen doesn't inherit from: (depending on the mappings you use)
* <ul>
* <li>net.minecraft.client.gui.screen.ingame.HandledScreen</li>
* <li>net.minecraft.client.gui.screen.inventory.ContainerScreen</li>
* <li>net.minecraft.client.gui.screens.inventory.AbstractContainerScreen</li>
* <li>May be others....</li>
* </ul>
* </li>
* <li>
* If your inventory screen follows the vanilla concepts of having slots that respect the stack
* limits it's probably already handled by IPN and you don't need to add it to the blacklist.
* </li>
* <li>
* The <code>slots</code> field/property is an empty. In other words the size is 0.
* </li>
* <li>
* If your screen inventory inherits:
* <ul>
* <li>EnchantingTable</li>
* <li>Anvil</li>
* <li>Beacon</li>
* <li>CartographyTable</li>
* <li>Grindstone</li>
* <li>Lectern</li>
* <li>Loom</li>
* <li>Stone Cutter</li>
* <li>Merchant</li>
* <li>CraftingTable</li>
* <li>Hopper</li>
* <li>BrewingStand</li>
* <li>Furnace and derivatives</li>
* </ul>
* </li>
* </ul>
*
* <h2>What to blacklist?</h2>
* Anything that does not fall into the above categories. For example all containers from Dank Storage mod
* MUST be blacklisted since they over-stack items and mouse clicks on a slot have different behaviour
* compared to vanilla containers.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IPNIgnore {
}
| /*
* MIT License
*
* Copyright (c) 2019-2020 jsnimda <<EMAIL>>
* Copyright (c) 2021-2022 <NAME>
*
* 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.IMPORT_0.mc.IMPORT_1.IMPORT_2;
import IMPORT_3.IMPORT_4.IMPORT_5.ElementType;
import IMPORT_3.IMPORT_4.IMPORT_5.IMPORT_6;
import IMPORT_3.IMPORT_4.IMPORT_5.IMPORT_7;
import IMPORT_3.IMPORT_4.IMPORT_5.Target;
/**
* This annotation should be used by interested mods to inform Inventory Profiles Next(IPN)
* that one or more of their screens are not to be treated as inventories.
*
* <h2>What NOT to blacklist?</h2>
* <ul>
* <li>
* If your screen doesn't inherit from: (depending on the mappings you use)
* <ul>
* <li>net.minecraft.client.gui.screen.ingame.HandledScreen</li>
* <li>net.minecraft.client.gui.screen.inventory.ContainerScreen</li>
* <li>net.minecraft.client.gui.screens.inventory.AbstractContainerScreen</li>
* <li>May be others....</li>
* </ul>
* </li>
* <li>
* If your inventory screen follows the vanilla concepts of having slots that respect the stack
* limits it's probably already handled by IPN and you don't need to add it to the blacklist.
* </li>
* <li>
* The <code>slots</code> field/property is an empty. In other words the size is 0.
* </li>
* <li>
* If your screen inventory inherits:
* <ul>
* <li>EnchantingTable</li>
* <li>Anvil</li>
* <li>Beacon</li>
* <li>CartographyTable</li>
* <li>Grindstone</li>
* <li>Lectern</li>
* <li>Loom</li>
* <li>Stone Cutter</li>
* <li>Merchant</li>
* <li>CraftingTable</li>
* <li>Hopper</li>
* <li>BrewingStand</li>
* <li>Furnace and derivatives</li>
* </ul>
* </li>
* </ul>
*
* <h2>What to blacklist?</h2>
* Anything that does not fall into the above categories. For example all containers from Dank Storage mod
* MUST be blacklisted since they over-stack items and mouse clicks on a slot have different behaviour
* compared to vanilla containers.
*/
@IMPORT_6(IMPORT_7.RUNTIME)
@Target(ElementType.VAR_0)
public @interface CLASS_0 {
}
| 0.539238 | {'IMPORT_0': 'anti_ad', 'IMPORT_1': 'ipn', 'IMPORT_2': 'api', 'IMPORT_3': 'java', 'IMPORT_4': 'lang', 'IMPORT_5': 'annotation', 'IMPORT_6': 'Retention', 'IMPORT_7': 'RetentionPolicy', 'VAR_0': 'TYPE', 'CLASS_0': 'IPNIgnore'} | java | Procedural | 99.78% |
/*
* Copyright (c) 2015, 2016 <NAME>, <NAME>,
* <NAME>, <NAME>
*
* 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 test.view;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import javafx.scene.canvas.GraphicsContext;
import view.GraphUtils;
@SuppressWarnings("static-method")
public class GraphUtilsTest {
@Test
public void test00() throws Throwable {
double double0 = GraphUtils.vecLengthSqr(0.0, 0.0);
assertEquals(0.0, double0, 0.01D);
}
@Test
public void test01() throws Throwable {
double double0 = GraphUtils.vecLength((-4624.37), (-4624.37));
assertEquals(6539.846771431269, double0, 0.01D);
}
@Test
public void test02() throws Throwable {
double double0 = GraphUtils.calcAngleOnCircle(1025.2694390987,
(-1113.31077555403), (-1113.31077555403));
assertEquals((-90.0), double0, 0.01D);
}
@Test
public void test03() throws Throwable {
double double0 = GraphUtils.arcCalcArcExtent(0.0, 360.0);
assertEquals(0.0, double0, 0.01D);
}
@Test
public void test04() throws Throwable {
// Undeclared exception!
try {
GraphUtils.fillArrowHead((GraphicsContext) null, (-1.0), (-2109.4),
(-1.0), (-1.0), (-2109.4));
fail("Expecting exception: NullPointerException");
} catch (NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void test05() throws Throwable {
double[] doubleArray0 = GraphUtils.vectorsAround(0.7071067811865476,
0.0, 2673.384);
assertArrayEquals(new double[] { 3780.735910231234, Double.NaN,
3780.735910231234, Double.NaN }, doubleArray0, 0.01);
}
@Test
public void test06() throws Throwable {
double[] doubleArray0 = GraphUtils.vectorsAround(0.0, 0.0,
(-69.5603967218878));
assertArrayEquals(
new double[] { Double.NEGATIVE_INFINITY, Double.NaN,
Double.NEGATIVE_INFINITY, Double.NaN },
doubleArray0, 0.01);
}
@Test
public void test07() throws Throwable {
boolean boolean0 = GraphUtils.isPointInArcSection(1681.3879471593905,
1681.3879471593905, 1681.3879471593905, 1681.3879471593905,
1681.3879471593905, 1681.3879471593905);
assertFalse(boolean0);
}
@Test
public void test08() throws Throwable {
double[] doubleArray0 = GraphUtils.calcCircleIntersectionPoints(
1264.18972536, 2.0, 0.0, 1264.18972536);
assertArrayEquals(new double[] { 1.0, 1264.1893298496836, 1.0,
(-1264.1893298496836) }, doubleArray0, 0.01);
}
@Test
public void test09() throws Throwable {
double[] doubleArray0 = GraphUtils
.calcCircleIntersectionPoints(639.5273, 0.0, 440.97, 0.0);
assertNull(doubleArray0);
}
@Test
public void test10() throws Throwable {
double double0 = GraphUtils.arcCalcArcExtent(180.0, 0.0);
assertEquals((-180.0), double0, 0.01D);
}
@Test
public void test11() throws Throwable {
double double0 = GraphUtils.calcTextAngle(2253.5, (-602.9008065610722),
(-602.9008065610722));
assertEquals((-90.0), double0, 0.01D);
}
@Test
public void test12() throws Throwable {
double double0 = GraphUtils.calcTextAngle(0.0, 639.5273, 639.5273);
assertEquals(270.0, double0, 0.01D);
}
@Test
public void test13() throws Throwable {
double double0 = GraphUtils.calcAngleOnCircle(3105.0, 0.0, 0.0);
assertEquals(Double.NaN, double0, 0.01D);
}
@Test
public void test14() throws Throwable {
double double0 = GraphUtils.vecLengthSqr(216.507, 216.507);
assertEquals(93750.56209800001, double0, 0.01D);
}
@Test
public void test15() throws Throwable {
GraphUtils.calcTextAngle((-397.9), (-397.9), 3092.1946);
GraphicsContext graphicsContext0 = null;
// Undeclared exception!
try {
GraphUtils.strokeCircleCentred((GraphicsContext) null, 3092.1946,
352.60674605759357, 352.60674605759357);
fail("Expecting exception: NullPointerException");
} catch (NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void test16() throws Throwable {
double[] doubleArray0 = new double[2];
// Undeclared exception!
try {
GraphUtils.filterArcIntersectionPoint(doubleArray0, 0.0, 0.0, 0.0,
0.0);
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch (ArrayIndexOutOfBoundsException e) {
//
// 2
//
}
}
@Test
public void test17() throws Throwable {
boolean boolean0 = GraphUtils.isPointInArcSection(639.5273, 2673.384,
0.0, 2366.24430903189, 2673.384, 2189.0);
assertTrue(boolean0);
}
@Test
public void test18() throws Throwable {
double double0 = GraphUtils.calcAngleOnCircle(1030.79, 3768.0,
(-839.2986785836));
assertEquals(Double.NaN, double0, 0.01D);
}
@Test
public void test19() throws Throwable {
double double0 = GraphUtils.calcAngleOnCircle((-509.4885013925),
(-509.4885013925), 0.026746158801103093);
assertEquals(Double.NaN, double0, 0.01D);
}
@Test
public void test20() throws Throwable {
double double0 = GraphUtils.vecLength(0.0, 0.0);
assertEquals(0.0, double0, 0.01D);
}
@Test
public void test21() throws Throwable {
double[] doubleArray0 = GraphUtils.vectorsAround(0.0, 0.0, (-1.0));
assertArrayEquals(new double[] { -0.0, -0.0 }, doubleArray0, 0.01);
}
@Test
public void test22() throws Throwable {
double[] doubleArray0 = GraphUtils.vectorsAround((-2938.101282),
(-530.273051980836), 2253.5);
double[] doubleArray1 = GraphUtils.filterArcIntersectionPoint(
doubleArray0, 174.85969426486, 396.5866203550845, 2253.5, 0.0);
assertNull(doubleArray1);
assertArrayEquals(
new double[] { (-0.626290353657779), (-0.7795898876429912),
(-0.8593024384085348), 0.5114678087085673 },
doubleArray0, 0.01);
}
@Test
public void test23() throws Throwable {
double[] doubleArray0 = GraphUtils.vectorsAround(1.0, 2.0, 0.0);
double[] doubleArray1 = GraphUtils.filterArcIntersectionPoint(
doubleArray0, (-559.79), 360.0, 360.0, 0.0);
assertNotNull(doubleArray1);
assertArrayEquals(
new double[] { 0.894427190999916, (-0.447213595499958) },
doubleArray1, 0.01);
}
@Test
public void test24() throws Throwable {
double[] doubleArray0 = GraphUtils.filterArcIntersectionPoint(
(double[]) null, 0.0, 2673.384, (-69.5603967218878), 0.0);
assertNull(doubleArray0);
}
@Test
public void test25() throws Throwable {
double[] doubleArray0 = GraphUtils.vectorsAround((-2938.101282),
(-530.273051980836), 2253.5);
double[] doubleArray1 = GraphUtils.filterArcIntersectionPoint(
doubleArray0, 2142.2059900281356, 396.5866203550845,
(-530.273051980836), 2142.2059900281356);
assertNotNull(doubleArray1);
assertArrayEquals(
new double[] { (-0.8593024384085348), 0.5114678087085673 },
doubleArray1, 0.01);
}
@Test
public void test26() throws Throwable {
double[] doubleArray0 = GraphUtils.calcCircleIntersectionPoints(
(-4624.37), (-4.025307475262816), (-4.025307475262816),
(-4624.37));
assertNotNull(doubleArray0);
assertArrayEquals(
new double[] { 3267.910112578727, (-3271.935420054267),
(-3271.935420054267), 3267.910112578727 },
doubleArray0, 0.01);
}
@Test
public void test27() throws Throwable {
double[] doubleArray0 = GraphUtils.calcCircleIntersectionPoints(
(-1509.7910697), (-1509.7910697), 0.0, 0.0);
assertArrayEquals(
new double[] { (-1509.7910697), 0.0, (-1509.7910697), -0.0 },
doubleArray0, 0.01);
}
@Test
public void test28() throws Throwable {
double double0 = GraphUtils.arcCalcArcExtent(4.0, (-282.0));
assertEquals(74.0, double0, 0.01D);
}
@Test
public void test29() throws Throwable {
double double0 = GraphUtils.arcCalcArcExtent(0.0, 3225.2396097237);
assertEquals(2865.2396097237, double0, 0.01D);
}
@Test
public void test30() throws Throwable {
double double0 = GraphUtils.arcCalcArcExtent(0.0, 180.0);
assertEquals(180.0, double0, 0.01D);
}
@Test
public void test31() throws Throwable {
double double0 = GraphUtils.calcTextAngle((-4.025307475262816), 0.0,
(-4.025307475262816));
assertEquals(0.0, double0, 0.01D);
}
@Test
public void test32() throws Throwable {
double double0 = GraphUtils.calcAngleOnCircle((-4213.239597772244),
216.507, 216.507);
assertEquals(270.0, double0, 0.01D);
}
@Test
public void test33() throws Throwable {
double double0 = GraphUtils.calcAngleOnCircle(0.0, 0.0,
(-3279.843072802703));
assertEquals(-0.0, double0, 0.01D);
}
@Test
public void test34() throws Throwable {
double double0 = GraphUtils.calcTextAngle((-1663.384671), (-2.0), 2.0);
assertEquals(90.0, double0, 0.01D);
}
@Test
public void test35() throws Throwable {
double double0 = GraphUtils.calcTextAngle(1298.682951836875,
1298.682951836875, (-1819.3));
assertEquals(405.54793641596405, double0, 0.01D);
}
@Test
public void test36() throws Throwable {
// Undeclared exception!
try {
GraphUtils.strokeCircleCentred((GraphicsContext) null, 0.0, 0.0,
0.0);
fail("Expecting exception: NullPointerException");
} catch (NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void test37() throws Throwable {
// Undeclared exception!
try {
GraphUtils.setGcRotation((GraphicsContext) null, (-1422.125802124),
0.0, 1817.115466);
fail("Expecting exception: NullPointerException");
} catch (NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void test38() throws Throwable {
// Undeclared exception!
try {
GraphUtils.fillCircleCentred((GraphicsContext) null, 0.0,
238624.06048649907, (-1551.39));
fail("Expecting exception: NullPointerException");
} catch (NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void test39() throws Throwable {
// Undeclared exception!
try {
GraphUtils.fillArrowHead((GraphicsContext) null, 0.0, 0.0, 0.0, 0.0,
0.0);
fail("Expecting exception: NullPointerException");
} catch (NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void test40() throws Throwable {
GraphUtils graphUtils0 = new GraphUtils();
}
}
| /*
* Copyright (c) 2015, 2016 <NAME>, <NAME>,
* <NAME>, <NAME>
*
* 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 IMPORT_0.view;
import static IMPORT_1.junit.IMPORT_2.IMPORT_3;
import static IMPORT_1.junit.IMPORT_2.IMPORT_4;
import static IMPORT_1.junit.IMPORT_2.IMPORT_5;
import static IMPORT_1.junit.IMPORT_2.IMPORT_6;
import static IMPORT_1.junit.IMPORT_2.IMPORT_7;
import static IMPORT_1.junit.IMPORT_2.IMPORT_8;
import static IMPORT_1.junit.IMPORT_2.IMPORT_9;
import IMPORT_1.junit.Test;
import IMPORT_10.IMPORT_11.IMPORT_12.IMPORT_13;
import view.IMPORT_14;
@VAR_0("static-method")
public class CLASS_0 {
@Test
public void FUNC_0() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_1(0.0, 0.0);
IMPORT_4(0.0, VAR_1, 0.01D);
}
@Test
public void FUNC_2() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_3((-4624.37), (-4624.37));
IMPORT_4(6539.846771431269, VAR_1, 0.01D);
}
@Test
public void FUNC_4() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_5(1025.2694390987,
(-1113.31077555403), (-1113.31077555403));
IMPORT_4((-90.0), VAR_1, 0.01D);
}
@Test
public void FUNC_6() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_7(0.0, 360.0);
IMPORT_4(0.0, VAR_1, 0.01D);
}
@Test
public void FUNC_8() throws CLASS_1 {
// Undeclared exception!
try {
IMPORT_14.FUNC_9((IMPORT_13) null, (-1.0), (-2109.4),
(-1.0), (-1.0), (-2109.4));
IMPORT_9("Expecting exception: NullPointerException");
} catch (CLASS_2 VAR_2) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void FUNC_10() throws CLASS_1 {
double[] VAR_3 = IMPORT_14.FUNC_11(0.7071067811865476,
0.0, 2673.384);
IMPORT_3(new double[] { 3780.735910231234, VAR_4.VAR_5,
3780.735910231234, VAR_4.VAR_5 }, VAR_3, 0.01);
}
@Test
public void FUNC_12() throws CLASS_1 {
double[] VAR_3 = IMPORT_14.FUNC_11(0.0, 0.0,
(-69.5603967218878));
IMPORT_3(
new double[] { VAR_4.VAR_6, VAR_4.VAR_5,
VAR_4.VAR_6, VAR_4.VAR_5 },
VAR_3, 0.01);
}
@Test
public void FUNC_13() throws CLASS_1 {
boolean VAR_7 = IMPORT_14.FUNC_14(1681.3879471593905,
1681.3879471593905, 1681.3879471593905, 1681.3879471593905,
1681.3879471593905, 1681.3879471593905);
IMPORT_5(VAR_7);
}
@Test
public void FUNC_15() throws CLASS_1 {
double[] VAR_3 = IMPORT_14.FUNC_16(
1264.18972536, 2.0, 0.0, 1264.18972536);
IMPORT_3(new double[] { 1.0, 1264.1893298496836, 1.0,
(-1264.1893298496836) }, VAR_3, 0.01);
}
@Test
public void FUNC_17() throws CLASS_1 {
double[] VAR_3 = IMPORT_14
.FUNC_16(639.5273, 0.0, 440.97, 0.0);
IMPORT_7(VAR_3);
}
@Test
public void FUNC_18() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_7(180.0, 0.0);
IMPORT_4((-180.0), VAR_1, 0.01D);
}
@Test
public void FUNC_19() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_20(2253.5, (-602.9008065610722),
(-602.9008065610722));
IMPORT_4((-90.0), VAR_1, 0.01D);
}
@Test
public void FUNC_21() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_20(0.0, 639.5273, 639.5273);
IMPORT_4(270.0, VAR_1, 0.01D);
}
@Test
public void FUNC_22() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_5(3105.0, 0.0, 0.0);
IMPORT_4(VAR_4.VAR_5, VAR_1, 0.01D);
}
@Test
public void FUNC_23() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_1(216.507, 216.507);
IMPORT_4(93750.56209800001, VAR_1, 0.01D);
}
@Test
public void FUNC_24() throws CLASS_1 {
IMPORT_14.FUNC_20((-397.9), (-397.9), 3092.1946);
IMPORT_13 VAR_8 = null;
// Undeclared exception!
try {
IMPORT_14.FUNC_25((IMPORT_13) null, 3092.1946,
352.60674605759357, 352.60674605759357);
IMPORT_9("Expecting exception: NullPointerException");
} catch (CLASS_2 VAR_2) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void FUNC_26() throws CLASS_1 {
double[] VAR_3 = new double[2];
// Undeclared exception!
try {
IMPORT_14.FUNC_27(VAR_3, 0.0, 0.0, 0.0,
0.0);
IMPORT_9("Expecting exception: ArrayIndexOutOfBoundsException");
} catch (CLASS_3 VAR_2) {
//
// 2
//
}
}
@Test
public void FUNC_28() throws CLASS_1 {
boolean VAR_7 = IMPORT_14.FUNC_14(639.5273, 2673.384,
0.0, 2366.24430903189, 2673.384, 2189.0);
IMPORT_8(VAR_7);
}
@Test
public void FUNC_29() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_5(1030.79, 3768.0,
(-839.2986785836));
IMPORT_4(VAR_4.VAR_5, VAR_1, 0.01D);
}
@Test
public void FUNC_30() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_5((-509.4885013925),
(-509.4885013925), 0.026746158801103093);
IMPORT_4(VAR_4.VAR_5, VAR_1, 0.01D);
}
@Test
public void FUNC_31() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_3(0.0, 0.0);
IMPORT_4(0.0, VAR_1, 0.01D);
}
@Test
public void FUNC_32() throws CLASS_1 {
double[] VAR_3 = IMPORT_14.FUNC_11(0.0, 0.0, (-1.0));
IMPORT_3(new double[] { -0.0, -0.0 }, VAR_3, 0.01);
}
@Test
public void FUNC_33() throws CLASS_1 {
double[] VAR_3 = IMPORT_14.FUNC_11((-2938.101282),
(-530.273051980836), 2253.5);
double[] VAR_9 = IMPORT_14.FUNC_27(
VAR_3, 174.85969426486, 396.5866203550845, 2253.5, 0.0);
IMPORT_7(VAR_9);
IMPORT_3(
new double[] { (-0.626290353657779), (-0.7795898876429912),
(-0.8593024384085348), 0.5114678087085673 },
VAR_3, 0.01);
}
@Test
public void FUNC_34() throws CLASS_1 {
double[] VAR_3 = IMPORT_14.FUNC_11(1.0, 2.0, 0.0);
double[] VAR_9 = IMPORT_14.FUNC_27(
VAR_3, (-559.79), 360.0, 360.0, 0.0);
IMPORT_6(VAR_9);
IMPORT_3(
new double[] { 0.894427190999916, (-0.447213595499958) },
VAR_9, 0.01);
}
@Test
public void test24() throws CLASS_1 {
double[] VAR_3 = IMPORT_14.FUNC_27(
(double[]) null, 0.0, 2673.384, (-69.5603967218878), 0.0);
IMPORT_7(VAR_3);
}
@Test
public void FUNC_35() throws CLASS_1 {
double[] VAR_3 = IMPORT_14.FUNC_11((-2938.101282),
(-530.273051980836), 2253.5);
double[] VAR_9 = IMPORT_14.FUNC_27(
VAR_3, 2142.2059900281356, 396.5866203550845,
(-530.273051980836), 2142.2059900281356);
IMPORT_6(VAR_9);
IMPORT_3(
new double[] { (-0.8593024384085348), 0.5114678087085673 },
VAR_9, 0.01);
}
@Test
public void FUNC_36() throws CLASS_1 {
double[] VAR_3 = IMPORT_14.FUNC_16(
(-4624.37), (-4.025307475262816), (-4.025307475262816),
(-4624.37));
IMPORT_6(VAR_3);
IMPORT_3(
new double[] { 3267.910112578727, (-3271.935420054267),
(-3271.935420054267), 3267.910112578727 },
VAR_3, 0.01);
}
@Test
public void FUNC_37() throws CLASS_1 {
double[] VAR_3 = IMPORT_14.FUNC_16(
(-1509.7910697), (-1509.7910697), 0.0, 0.0);
IMPORT_3(
new double[] { (-1509.7910697), 0.0, (-1509.7910697), -0.0 },
VAR_3, 0.01);
}
@Test
public void FUNC_38() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_7(4.0, (-282.0));
IMPORT_4(74.0, VAR_1, 0.01D);
}
@Test
public void test29() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_7(0.0, 3225.2396097237);
IMPORT_4(2865.2396097237, VAR_1, 0.01D);
}
@Test
public void FUNC_39() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_7(0.0, 180.0);
IMPORT_4(180.0, VAR_1, 0.01D);
}
@Test
public void FUNC_40() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_20((-4.025307475262816), 0.0,
(-4.025307475262816));
IMPORT_4(0.0, VAR_1, 0.01D);
}
@Test
public void FUNC_41() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_5((-4213.239597772244),
216.507, 216.507);
IMPORT_4(270.0, VAR_1, 0.01D);
}
@Test
public void FUNC_42() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_5(0.0, 0.0,
(-3279.843072802703));
IMPORT_4(-0.0, VAR_1, 0.01D);
}
@Test
public void FUNC_43() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_20((-1663.384671), (-2.0), 2.0);
IMPORT_4(90.0, VAR_1, 0.01D);
}
@Test
public void FUNC_44() throws CLASS_1 {
double VAR_1 = IMPORT_14.FUNC_20(1298.682951836875,
1298.682951836875, (-1819.3));
IMPORT_4(405.54793641596405, VAR_1, 0.01D);
}
@Test
public void FUNC_45() throws CLASS_1 {
// Undeclared exception!
try {
IMPORT_14.FUNC_25((IMPORT_13) null, 0.0, 0.0,
0.0);
IMPORT_9("Expecting exception: NullPointerException");
} catch (CLASS_2 VAR_2) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void FUNC_46() throws CLASS_1 {
// Undeclared exception!
try {
IMPORT_14.FUNC_47((IMPORT_13) null, (-1422.125802124),
0.0, 1817.115466);
IMPORT_9("Expecting exception: NullPointerException");
} catch (CLASS_2 VAR_2) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void FUNC_48() throws CLASS_1 {
// Undeclared exception!
try {
IMPORT_14.FUNC_49((IMPORT_13) null, 0.0,
238624.06048649907, (-1551.39));
IMPORT_9("Expecting exception: NullPointerException");
} catch (CLASS_2 VAR_2) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void FUNC_50() throws CLASS_1 {
// Undeclared exception!
try {
IMPORT_14.FUNC_9((IMPORT_13) null, 0.0, 0.0, 0.0, 0.0,
0.0);
IMPORT_9("Expecting exception: NullPointerException");
} catch (CLASS_2 VAR_2) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test
public void test40() throws CLASS_1 {
IMPORT_14 VAR_10 = new IMPORT_14();
}
}
| 0.904096 | {'IMPORT_0': 'test', 'IMPORT_1': 'org', 'IMPORT_2': 'Assert', 'IMPORT_3': 'assertArrayEquals', 'IMPORT_4': 'assertEquals', 'IMPORT_5': 'assertFalse', 'IMPORT_6': 'assertNotNull', 'IMPORT_7': 'assertNull', 'IMPORT_8': 'assertTrue', 'IMPORT_9': 'fail', 'IMPORT_10': 'javafx', 'IMPORT_11': 'scene', 'IMPORT_12': 'canvas', 'IMPORT_13': 'GraphicsContext', 'IMPORT_14': 'GraphUtils', 'VAR_0': 'SuppressWarnings', 'CLASS_0': 'GraphUtilsTest', 'FUNC_0': 'test00', 'CLASS_1': 'Throwable', 'VAR_1': 'double0', 'FUNC_1': 'vecLengthSqr', 'FUNC_2': 'test01', 'FUNC_3': 'vecLength', 'FUNC_4': 'test02', 'FUNC_5': 'calcAngleOnCircle', 'FUNC_6': 'test03', 'FUNC_7': 'arcCalcArcExtent', 'FUNC_8': 'test04', 'FUNC_9': 'fillArrowHead', 'CLASS_2': 'NullPointerException', 'VAR_2': 'e', 'FUNC_10': 'test05', 'VAR_3': 'doubleArray0', 'FUNC_11': 'vectorsAround', 'VAR_4': 'Double', 'VAR_5': 'NaN', 'FUNC_12': 'test06', 'VAR_6': 'NEGATIVE_INFINITY', 'FUNC_13': 'test07', 'VAR_7': 'boolean0', 'FUNC_14': 'isPointInArcSection', 'FUNC_15': 'test08', 'FUNC_16': 'calcCircleIntersectionPoints', 'FUNC_17': 'test09', 'FUNC_18': 'test10', 'FUNC_19': 'test11', 'FUNC_20': 'calcTextAngle', 'FUNC_21': 'test12', 'FUNC_22': 'test13', 'FUNC_23': 'test14', 'FUNC_24': 'test15', 'VAR_8': 'graphicsContext0', 'FUNC_25': 'strokeCircleCentred', 'FUNC_26': 'test16', 'FUNC_27': 'filterArcIntersectionPoint', 'CLASS_3': 'ArrayIndexOutOfBoundsException', 'FUNC_28': 'test17', 'FUNC_29': 'test18', 'FUNC_30': 'test19', 'FUNC_31': 'test20', 'FUNC_32': 'test21', 'FUNC_33': 'test22', 'VAR_9': 'doubleArray1', 'FUNC_34': 'test23', 'FUNC_35': 'test25', 'FUNC_36': 'test26', 'FUNC_37': 'test27', 'FUNC_38': 'test28', 'FUNC_39': 'test30', 'FUNC_40': 'test31', 'FUNC_41': 'test32', 'FUNC_42': 'test33', 'FUNC_43': 'test34', 'FUNC_44': 'test35', 'FUNC_45': 'test36', 'FUNC_46': 'test37', 'FUNC_47': 'setGcRotation', 'FUNC_48': 'test38', 'FUNC_49': 'fillCircleCentred', 'FUNC_50': 'test39', 'VAR_10': 'graphUtils0'} | java | Hibrido | 18.76% |
package jacobgc.grafx.grafxngine.render_engine;
/**
* Created by JacobGC on 5/24/2016.
*/
public class RawModel {
}
| package jacobgc.grafx.grafxngine.render_engine;
/**
* Created by JacobGC on 5/24/2016.
*/
public class CLASS_0 {
}
| 0.094524 | {'CLASS_0': 'RawModel'} | java | OOP | 100.00% |
/**
* Report and attempt to recover from {@code e}. Returns a new HTTP engine
* that should be used for the retry if {@code e} is recoverable, or null if
* the failure is permanent.
*/
public HttpEngine recover(IOException e) {
if (routeSelector != null && connection != null) {
routeSelector.connectFailed(connection, e);
}
boolean canRetryRequestBody = requestBodyOut == null || requestBodyOut instanceof RetryableSink;
if (routeSelector == null && connection == null
|| routeSelector != null && !routeSelector.hasNext()
|| !isRecoverable(e)
|| !canRetryRequestBody) {
return null;
}
Connection connection = close();
return new HttpEngine(client, userRequest, bufferRequestBody, connection, routeSelector,
(RetryableSink) requestBodyOut, priorResponse);
} | /**
* Report and attempt to recover from {@code e}. Returns a new HTTP engine
* that should be used for the retry if {@code e} is recoverable, or null if
* the failure is permanent.
*/
public HttpEngine FUNC_0(CLASS_0 e) {
if (VAR_0 != null && VAR_1 != null) {
VAR_0.FUNC_1(VAR_1, e);
}
boolean VAR_2 = VAR_3 == null || VAR_3 instanceof RetryableSink;
if (VAR_0 == null && VAR_1 == null
|| VAR_0 != null && !VAR_0.FUNC_2()
|| !FUNC_3(e)
|| !VAR_2) {
return null;
}
CLASS_1 VAR_1 = FUNC_4();
return new HttpEngine(client, VAR_4, VAR_5, VAR_1, VAR_0,
(RetryableSink) VAR_3, VAR_6);
} | 0.847321 | {'FUNC_0': 'recover', 'CLASS_0': 'IOException', 'VAR_0': 'routeSelector', 'VAR_1': 'connection', 'FUNC_1': 'connectFailed', 'VAR_2': 'canRetryRequestBody', 'VAR_3': 'requestBodyOut', 'FUNC_2': 'hasNext', 'FUNC_3': 'isRecoverable', 'CLASS_1': 'Connection', 'FUNC_4': 'close', 'VAR_4': 'userRequest', 'VAR_5': 'bufferRequestBody', 'VAR_6': 'priorResponse'} | java | Texto | 6.42% |
package dtri.com.tw.service;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import dtri.com.tw.bean.PackageBean;
import dtri.com.tw.db.entity.SystemUser;
import dtri.com.tw.db.entity.WorkType;
import dtri.com.tw.db.pgsql.dao.WorkTypeDao;
import dtri.com.tw.tools.Fm_Time;
@Service
public class WorkTypeService {
@Autowired
private WorkTypeDao workDao;
// 取得當前 資料清單
public PackageBean getData(JSONObject body, int page, int p_size) {
PackageBean bean = new PackageBean();
ArrayList<WorkType> workTypes = new ArrayList<WorkType>();
// 查詢的頁數,page=從0起算/size=查詢的每頁筆數
if (p_size < 1) {
page = 0;
p_size = 100;
}
PageRequest page_r = PageRequest.of(page, p_size, Sort.by("wtid").descending());
String wt_name = null;
String status = "0";
// 初次載入需要標頭 / 之後就不用
if (body == null || body.isNull("search")) {
// 放入包裝(header) [01 是排序][_h__ 是分割直][資料庫欄位名稱]
JSONObject object_header = new JSONObject();
int ord = 0;
object_header.put(FFS.ord((ord += 1), FFM.Hmb.H) + "wt_id", FFS.h_t("ID", "100px", FFM.Wri.W_N));
object_header.put(FFS.ord((ord += 1), FFM.Hmb.H) + "wt_name", FFS.h_t("工作類型名稱", "200px", FFM.Wri.W_Y));
object_header.put(FFS.ord((ord += 1), FFM.Hmb.H) + "sys_c_date", FFS.h_t("建立時間", "180px", FFM.Wri.W_Y));
object_header.put(FFS.ord((ord += 1), FFM.Hmb.H) + "sys_c_user", FFS.h_t("建立人", "100px", FFM.Wri.W_Y));
object_header.put(FFS.ord((ord += 1), FFM.Hmb.H) + "sys_m_date", FFS.h_t("修改時間", "180px", FFM.Wri.W_Y));
object_header.put(FFS.ord((ord += 1), FFM.Hmb.H) + "sys_m_user", FFS.h_t("修改人", "100px", FFM.Wri.W_Y));
object_header.put(FFS.ord((ord += 1), FFM.Hmb.H) + "sys_sort", FFS.h_t("排序", "100px", FFM.Wri.W_N));
object_header.put(FFS.ord((ord += 1), FFM.Hmb.H) + "sys_ver", FFS.h_t("版本", "100px", FFM.Wri.W_N));
object_header.put(FFS.ord((ord += 1), FFM.Hmb.H) + "sys_status", FFS.h_t("狀態", "100px", FFM.Wri.W_N));
object_header.put(FFS.ord((ord += 1), FFM.Hmb.H) + "sys_note", FFS.h_t("備註", "300px", FFM.Wri.W_Y));
bean.setHeader(object_header);
// 放入修改 [(key)](modify/Create/Delete) 格式
JSONArray obj_m = new JSONArray();
JSONArray n_val = new JSONArray();
JSONArray a_val = new JSONArray();
obj_m.put(FFS.h_m(FFM.Dno.D_N, FFM.Tag.INP, FFM.Type.TEXT, "", "", FFM.Wri.W_N, "col-md-1", false, n_val, "wt_id", "ID"));
obj_m.put(FFS.h_m(FFM.Dno.D_S, FFM.Tag.INP, FFM.Type.TEXT, "", "", FFM.Wri.W_Y, "col-md-3", false, n_val, "wt_name", "工作類型名稱"));
obj_m.put(FFS.h_m(FFM.Dno.D_S, FFM.Tag.INP, FFM.Type.TEXT, "", "", FFM.Wri.W_Y, "col-md-8", false, n_val, "sys_note", "備註"));
obj_m.put(FFS.h_m(FFM.Dno.D_N, FFM.Tag.INP, FFM.Type.NUMB, "0", "0", FFM.Wri.W_Y, "col-md-1", true, n_val, "sys_sort", "排序"));
obj_m.put(FFS.h_m(FFM.Dno.D_N, FFM.Tag.INP, FFM.Type.NUMB, "0", "0", FFM.Wri.W_N, "col-md-1", false, n_val, "sys_ver", "版本"));
a_val = new JSONArray();
a_val.put((new JSONObject()).put("value", "正常").put("key", "0"));
a_val.put((new JSONObject()).put("value", "異常").put("key", "1"));
obj_m.put(FFS.h_m(FFM.Dno.D_S, FFM.Tag.SEL, FFM.Type.TEXT, "", "0", FFM.Wri.W_Y, "col-md-1", true, a_val, "sys_status", "狀態"));
bean.setCell_modify(obj_m);
// 放入包裝(search)
JSONArray object_searchs = new JSONArray();
object_searchs.put(FFS.h_s(FFM.Tag.INP, FFM.Type.TEXT, "", "col-md-2", "wt_name", "名稱", n_val));
a_val = new JSONArray();
a_val.put((new JSONObject()).put("value", "正常").put("key", "0"));
a_val.put((new JSONObject()).put("value", "異常").put("key", "1"));
object_searchs.put(FFS.h_s(FFM.Tag.SEL, FFM.Type.TEXT, "0", "col-md-2", "sys_status", "狀態", a_val));
bean.setCell_searchs(object_searchs);
} else {
// 進行-特定查詢
wt_name = body.getJSONObject("search").getString("wt_name");
wt_name = wt_name.equals("") ? null : wt_name;
status = body.getJSONObject("search").getString("sys_status");
status = status.equals("") ? "0" : status;
}
workTypes = workDao.findAllByWorkType(wt_name, Integer.parseInt(status), page_r);
// 放入包裝(body) [01 是排序][_b__ 是分割直][資料庫欄位名稱]
JSONArray object_bodys = new JSONArray();
workTypes.forEach(one -> {
JSONObject object_body = new JSONObject();
int ord = 0;
object_body.put(FFS.ord((ord += 1), FFM.Hmb.B) + "wt_id", one.getWtid());
object_body.put(FFS.ord((ord += 1), FFM.Hmb.B) + "wt_name", one.getWtname());
object_body.put(FFS.ord((ord += 1), FFM.Hmb.B) + "sys_c_date", Fm_Time.to_yMd_Hms(one.getSyscdate()));
object_body.put(FFS.ord((ord += 1), FFM.Hmb.B) + "sys_c_user", one.getSyscuser());
object_body.put(FFS.ord((ord += 1), FFM.Hmb.B) + "sys_m_date", Fm_Time.to_yMd_Hms(one.getSysmdate()));
object_body.put(FFS.ord((ord += 1), FFM.Hmb.B) + "sys_m_user", one.getSysmuser());
object_body.put(FFS.ord((ord += 1), FFM.Hmb.B) + "sys_sort", one.getSyssort());
object_body.put(FFS.ord((ord += 1), FFM.Hmb.B) + "sys_ver", one.getSysver());
object_body.put(FFS.ord((ord += 1), FFM.Hmb.B) + "sys_status", one.getSysstatus());
object_body.put(FFS.ord((ord += 1), FFM.Hmb.B) + "sys_note", one.getSysnote());
object_bodys.put(object_body);
});
bean.setBody(new JSONObject().put("search", object_bodys));
return bean;
}
// 存檔 資料清單
@Transactional
public boolean createData(JSONObject body, SystemUser user) {
boolean check = false;
try {
JSONArray list = body.getJSONArray("create");
for (Object one : list) {
// 物件轉換
WorkType sys_c = new WorkType();
JSONObject data = (JSONObject) one;
sys_c.setWtname(data.getString("wt_name"));
sys_c.setSysnote(data.has("sys_note") ? data.getString("sys_note") : "");
sys_c.setSyssort(data.getInt("sys_sort"));
sys_c.setSysstatus(data.getInt("sys_status"));
sys_c.setSysmuser(user.getSuaccount());
sys_c.setSyscuser(user.getSuaccount());
workDao.save(sys_c);
}
check = true;
} catch (Exception e) {
System.out.println(e);
}
return check;
}
// 存檔 資料清單
@Transactional
public boolean save_asData(JSONObject body, SystemUser user) {
boolean check = false;
try {
JSONArray list = body.getJSONArray("save_as");
for (Object one : list) {
// 物件轉換
WorkType sys_c = new WorkType();
JSONObject data = (JSONObject) one;
sys_c.setWtname(data.getString("wt_name"));
sys_c.setSysnote(data.has("sys_note") ? data.getString("sys_note") : "");
sys_c.setSyssort(data.getInt("sys_sort"));
sys_c.setSysstatus(data.getInt("sys_status"));
sys_c.setSysmuser(user.getSuaccount());
sys_c.setSyscuser(user.getSuaccount());
workDao.save(sys_c);
}
check = true;
} catch (Exception e) {
System.out.println(e);
}
return check;
}
// 更新 資料清單
@Transactional
public boolean updateData(JSONObject body, SystemUser user) {
boolean check = false;
try {
JSONArray list = body.getJSONArray("modify");
for (Object one : list) {
// 物件轉換
WorkType sys_p = new WorkType();
JSONObject data = (JSONObject) one;
sys_p.setWtid(data.getLong("wt_id"));
sys_p.setWtname(data.getString("wt_name"));
sys_p.setSysnote(data.has("sys_note") ? data.getString("sys_note") : "");
sys_p.setSyssort(data.getInt("sys_sort"));
sys_p.setSysstatus(data.getInt("sys_status"));
sys_p.setSysmuser(user.getSuaccount());
sys_p.setSysmdate(new Date());
workDao.save(sys_p);
}
// 有更新才正確
if (list.length() > 0) {
check = true;
}
} catch (Exception e) {
System.out.println(e);
return false;
}
return check;
}
// 移除 資料清單
@Transactional
public boolean deleteData(JSONObject body) {
boolean check = false;
try {
JSONArray list = body.getJSONArray("delete");
for (Object one : list) {
// 物件轉換
WorkType sys_p = new WorkType();
JSONObject data = (JSONObject) one;
sys_p.setWtid(data.getLong("wt_id"));
workDao.deleteByWtid(sys_p.getWtid());
check = true;
}
} catch (Exception e) {
System.out.println(e);
return false;
}
return check;
}
}
| package IMPORT_0.IMPORT_1.tw.IMPORT_2;
import IMPORT_3.util.IMPORT_4;
import IMPORT_3.util.Date;
import org.json.IMPORT_5;
import org.json.IMPORT_6;
import org.springframework.IMPORT_7.IMPORT_8.IMPORT_9.Autowired;
import org.springframework.IMPORT_10.domain.IMPORT_11;
import org.springframework.IMPORT_10.domain.IMPORT_12;
import org.springframework.IMPORT_13.IMPORT_14;
import org.springframework.transaction.IMPORT_9.Transactional;
import IMPORT_0.IMPORT_1.tw.IMPORT_15.PackageBean;
import IMPORT_0.IMPORT_1.tw.IMPORT_16.IMPORT_17.SystemUser;
import IMPORT_0.IMPORT_1.tw.IMPORT_16.IMPORT_17.WorkType;
import IMPORT_0.IMPORT_1.tw.IMPORT_16.pgsql.IMPORT_18.IMPORT_19;
import IMPORT_0.IMPORT_1.tw.IMPORT_20.IMPORT_21;
@IMPORT_14
public class CLASS_0 {
@Autowired
private IMPORT_19 VAR_0;
// 取得當前 資料清單
public PackageBean FUNC_0(IMPORT_6 VAR_1, int page, int VAR_2) {
PackageBean IMPORT_15 = new PackageBean();
IMPORT_4<WorkType> VAR_3 = new IMPORT_4<WorkType>();
// 查詢的頁數,page=從0起算/size=查詢的每頁筆數
if (VAR_2 < 1) {
page = 0;
VAR_2 = 100;
}
IMPORT_11 VAR_4 = IMPORT_11.FUNC_1(page, VAR_2, IMPORT_12.by("wtid").descending());
CLASS_1 wt_name = null;
CLASS_1 VAR_5 = "0";
// 初次載入需要標頭 / 之後就不用
if (VAR_1 == null || VAR_1.isNull("search")) {
// 放入包裝(header) [01 是排序][_h__ 是分割直][資料庫欄位名稱]
IMPORT_6 VAR_6 = new IMPORT_6();
int ord = 0;
VAR_6.put(FFS.ord((ord += 1), VAR_7.Hmb.H) + "wt_id", FFS.FUNC_2("ID", "100px", VAR_7.Wri.VAR_8));
VAR_6.put(FFS.ord((ord += 1), VAR_7.Hmb.H) + "wt_name", FFS.FUNC_2("工作類型名稱", "200px", FFM.Wri.W_Y)VAR_9
VAR_6.put(FFS.ord((ord += 1), VAR_7.Hmb.H) + "sys_c_date", FFS.FUNC_2("建立時間", "180px", FFM.Wri.VAR_10)VAR_9 VAR_6.put(FFS.ord((ord += 1), VAR_7.Hmb.H) + "sys_c_user", FFS.FUNC_2("建立人", "100px", FFM.Wri.W_VAR_11;
VAR_6.put(FFS.ord((ord += 1), VAR_7.Hmb.H) + "sys_m_date", FFS.FUNC_2("修改時間", "180px", FFM.Wri.VAR_10)VAR_9 VAR_6.put(FFS.ord((ord += 1), VAR_7.Hmb.H) + "sys_m_user", FFS.FUNC_2("修改人", "100px", FFM.Wri.W_VAR_11;
VAR_6.put(FFS.ord((ord += 1), VAR_7.Hmb.H) + "sys_sort", FFS.FUNC_2("排序", "100px", FFM.Wri.VAR_8)VAR_9 VAR_6.put(FFS.ord((ord += 1), VAR_7.Hmb.H) + "sys_ver", FFS.FUNC_2("版本", "100px", FFM.Wri.VAR_8)VAR_9 VAR_6.put(FFS.ord((ord += 1), VAR_7.Hmb.H) + "sys_status", FFS.FUNC_2("狀態", "100px", FFM.Wri.VAR_8)VAR_9 VAR_6.put(FFS.ord((ord += 1), VAR_7.Hmb.H) + "sys_note", FFS.FUNC_2("備註", "300px", FFM.Wri.VAR_10)VAR_9 IMPORT_15.setHeader(VAR_6);
// 放入修改 [(key)](modify/Create/Delete) 格式
IMPORT_5 obj_m = new IMPORT_5();
IMPORT_5 VAR_12 = new IMPORT_5();
IMPORT_5 a_val = new IMPORT_5();
obj_m.put(FFS.FUNC_3(VAR_7.VAR_13.VAR_14, VAR_7.VAR_15.VAR_16, VAR_7.Type.TEXT, "", "", VAR_7.Wri.VAR_8, "col-md-1", false, VAR_12, "wt_id", "ID"));
obj_m.put(FFS.FUNC_3(VAR_7.VAR_13.D_S, VAR_7.VAR_15.VAR_16, VAR_7.Type.TEXT, "", "", VAR_7.Wri.VAR_10, "col-md-3", false, VAR_12, "wt_name", "工作類型名稱"));
obj_m.put(FFS.FUNC_3(VAR_7.VAR_13.D_S, VAR_7.VAR_15.VAR_16, VAR_7.Type.TEXT, "", "", VAR_7.Wri.VAR_10, "col-md-8", false, VAR_12, "sys_note", "備註"));
obj_m.put(FFS.FUNC_3(VAR_7.VAR_13.VAR_14, VAR_7.VAR_15.VAR_16, VAR_7.Type.VAR_17, "0", "0", VAR_7.Wri.VAR_10, "col-md-1", true, VAR_12, "sys_sort", "排序"));
obj_m.put(FFS.FUNC_3(VAR_7.VAR_13.VAR_14, VAR_7.VAR_15.VAR_16, VAR_7.Type.VAR_17, "0", "0", VAR_7.Wri.VAR_8, "col-md-1", false, VAR_12, "sys_ver", "版本"));
a_val = new IMPORT_5();
a_val.put((new IMPORT_6()).put("value", "正常").put("key", "0"));
a_val.put((new IMPORT_6()).put("value", "異常").put("key", "1"));
obj_m.put(FFS.FUNC_3(VAR_7.VAR_13.D_S, VAR_7.VAR_15.SEL, VAR_7.Type.TEXT, "", "0", VAR_7.Wri.VAR_10, "col-md-1", true, a_val, "sys_status", "狀態"));
IMPORT_15.FUNC_4(obj_m);
// 放入包裝(search)
IMPORT_5 VAR_18 = new IMPORT_5();
VAR_18.put(FFS.h_s(VAR_7.VAR_15.VAR_16, VAR_7.Type.TEXT, "", "col-md-2", "wt_name", "名稱", n_vaVAR_19
a_val = new IMPORT_5();
a_val.put((new IMPORT_6()).put("value", "正常").put("key", "0"));
a_val.put((new IMPORT_6()).put("value", "異常").put("key", "1"));
VAR_18.put(FFS.h_s(VAR_7.VAR_15.SEL, VAR_7.Type.TEXT, "0", "col-md-2", "sys_status", "狀態", a_vaVAR_19 IMPORT_15.FUNC_5(VAR_18);
} else {
// 進行-特定查詢
wt_name = VAR_1.FUNC_6("search").FUNC_7("wt_name");
wt_name = wt_name.FUNC_8("") ? null : wt_name;
VAR_5 = VAR_1.FUNC_6("search").FUNC_7("sys_status");
VAR_5 = VAR_5.FUNC_8("") ? "0" : VAR_5;
}
VAR_3 = VAR_0.findAllByWorkType(wt_name, Integer.parseInt(VAR_5), VAR_4);
// 放入包裝(body) [01 是排序][_b__ 是分割直][資料庫欄位名稱]
IMPORT_5 VAR_20 = new IMPORT_5();
VAR_3.FUNC_9(one -> {
IMPORT_6 object_body = new IMPORT_6();
int ord = 0;
object_body.put(FFS.ord((ord += 1), VAR_7.Hmb.B) + "wt_id", one.getWtid());
object_body.put(FFS.ord((ord += 1), VAR_7.Hmb.B) + "wt_name", one.getWtname());
object_body.put(FFS.ord((ord += 1), VAR_7.Hmb.B) + "sys_c_date", IMPORT_21.FUNC_10(one.FUNC_11()));
object_body.put(FFS.ord((ord += 1), VAR_7.Hmb.B) + "sys_c_user", one.FUNC_12());
object_body.put(FFS.ord((ord += 1), VAR_7.Hmb.B) + "sys_m_date", IMPORT_21.FUNC_10(one.getSysmdate()));
object_body.put(FFS.ord((ord += 1), VAR_7.Hmb.B) + "sys_m_user", one.getSysmuser());
object_body.put(FFS.ord((ord += 1), VAR_7.Hmb.B) + "sys_sort", one.getSyssort());
object_body.put(FFS.ord((ord += 1), VAR_7.Hmb.B) + "sys_ver", one.FUNC_13());
object_body.put(FFS.ord((ord += 1), VAR_7.Hmb.B) + "sys_status", one.getSysstatus());
object_body.put(FFS.ord((ord += 1), VAR_7.Hmb.B) + "sys_note", one.getSysnote());
VAR_20.put(object_body);
});
IMPORT_15.setBody(new IMPORT_6().put("search", VAR_20));
return IMPORT_15;
}
// 存檔 資料清單
@Transactional
public boolean FUNC_14(IMPORT_6 VAR_1, SystemUser VAR_21) {
boolean VAR_22 = false;
try {
IMPORT_5 VAR_23 = VAR_1.getJSONArray("create");
for (CLASS_2 one : VAR_23) {
// 物件轉換
WorkType VAR_24 = new WorkType();
IMPORT_6 IMPORT_10 = (IMPORT_6) one;
VAR_24.FUNC_15(IMPORT_10.FUNC_7("wt_name"));
VAR_24.setSysnote(IMPORT_10.has("sys_note") ? IMPORT_10.FUNC_7("sys_note") : "");
VAR_24.setSyssort(IMPORT_10.getInt("sys_sort"));
VAR_24.FUNC_16(IMPORT_10.getInt("sys_status"));
VAR_24.FUNC_17(VAR_21.FUNC_18());
VAR_24.FUNC_19(VAR_21.FUNC_18());
VAR_0.save(VAR_24);
}
VAR_22 = true;
} catch (CLASS_3 VAR_25) {
System.out.println(VAR_25);
}
return VAR_22;
}
// 存檔 資料清單
@Transactional
public boolean FUNC_20(IMPORT_6 VAR_1, SystemUser VAR_21) {
boolean VAR_22 = false;
try {
IMPORT_5 VAR_23 = VAR_1.getJSONArray("save_as");
for (CLASS_2 one : VAR_23) {
// 物件轉換
WorkType VAR_24 = new WorkType();
IMPORT_6 IMPORT_10 = (IMPORT_6) one;
VAR_24.FUNC_15(IMPORT_10.FUNC_7("wt_name"));
VAR_24.setSysnote(IMPORT_10.has("sys_note") ? IMPORT_10.FUNC_7("sys_note") : "");
VAR_24.setSyssort(IMPORT_10.getInt("sys_sort"));
VAR_24.FUNC_16(IMPORT_10.getInt("sys_status"));
VAR_24.FUNC_17(VAR_21.FUNC_18());
VAR_24.FUNC_19(VAR_21.FUNC_18());
VAR_0.save(VAR_24);
}
VAR_22 = true;
} catch (CLASS_3 VAR_25) {
System.out.println(VAR_25);
}
return VAR_22;
}
// 更新 資料清單
@Transactional
public boolean FUNC_21(IMPORT_6 VAR_1, SystemUser VAR_21) {
boolean VAR_22 = false;
try {
IMPORT_5 VAR_23 = VAR_1.getJSONArray("modify");
for (CLASS_2 one : VAR_23) {
// 物件轉換
WorkType sys_p = new WorkType();
IMPORT_6 IMPORT_10 = (IMPORT_6) one;
sys_p.FUNC_22(IMPORT_10.getLong("wt_id"));
sys_p.FUNC_15(IMPORT_10.FUNC_7("wt_name"));
sys_p.setSysnote(IMPORT_10.has("sys_note") ? IMPORT_10.FUNC_7("sys_note") : "");
sys_p.setSyssort(IMPORT_10.getInt("sys_sort"));
sys_p.FUNC_16(IMPORT_10.getInt("sys_status"));
sys_p.FUNC_17(VAR_21.FUNC_18());
sys_p.setSysmdate(new Date());
VAR_0.save(sys_p);
}
// 有更新才正確
if (VAR_23.FUNC_23() > 0) {
VAR_22 = true;
}
} catch (CLASS_3 VAR_25) {
System.out.println(VAR_25);
return false;
}
return VAR_22;
}
// 移除 資料清單
@Transactional
public boolean deleteData(IMPORT_6 VAR_1) {
boolean VAR_22 = false;
try {
IMPORT_5 VAR_23 = VAR_1.getJSONArray("delete");
for (CLASS_2 one : VAR_23) {
// 物件轉換
WorkType sys_p = new WorkType();
IMPORT_6 IMPORT_10 = (IMPORT_6) one;
sys_p.FUNC_22(IMPORT_10.getLong("wt_id"));
VAR_0.FUNC_24(sys_p.getWtid());
VAR_22 = true;
}
} catch (CLASS_3 VAR_25) {
System.out.println(VAR_25);
return false;
}
return VAR_22;
}
}
| 0.622545 | {'IMPORT_0': 'dtri', 'IMPORT_1': 'com', 'IMPORT_2': 'service', 'IMPORT_3': 'java', 'IMPORT_4': 'ArrayList', 'IMPORT_5': 'JSONArray', 'IMPORT_6': 'JSONObject', 'IMPORT_7': 'beans', 'IMPORT_8': 'factory', 'IMPORT_9': 'annotation', 'IMPORT_10': 'data', 'IMPORT_11': 'PageRequest', 'IMPORT_12': 'Sort', 'IMPORT_13': 'stereotype', 'IMPORT_14': 'Service', 'IMPORT_15': 'bean', 'IMPORT_16': 'db', 'IMPORT_17': 'entity', 'IMPORT_18': 'dao', 'IMPORT_19': 'WorkTypeDao', 'IMPORT_20': 'tools', 'IMPORT_21': 'Fm_Time', 'CLASS_0': 'WorkTypeService', 'VAR_0': 'workDao', 'FUNC_0': 'getData', 'VAR_1': 'body', 'VAR_2': 'p_size', 'VAR_3': 'workTypes', 'VAR_4': 'page_r', 'FUNC_1': 'of', 'CLASS_1': 'String', 'VAR_5': 'status', 'VAR_6': 'object_header', 'VAR_7': 'FFM', 'FUNC_2': 'h_t', 'VAR_8': 'W_N', 'VAR_9': ');\n', 'VAR_10': 'W_Y', 'VAR_11': 'Y))', 'VAR_12': 'n_val', 'FUNC_3': 'h_m', 'VAR_13': 'Dno', 'VAR_14': 'D_N', 'VAR_15': 'Tag', 'VAR_16': 'INP', 'VAR_17': 'NUMB', 'FUNC_4': 'setCell_modify', 'VAR_18': 'object_searchs', 'VAR_19': 'l));\n', 'FUNC_5': 'setCell_searchs', 'FUNC_6': 'getJSONObject', 'FUNC_7': 'getString', 'FUNC_8': 'equals', 'VAR_20': 'object_bodys', 'FUNC_9': 'forEach', 'FUNC_10': 'to_yMd_Hms', 'FUNC_11': 'getSyscdate', 'FUNC_12': 'getSyscuser', 'FUNC_13': 'getSysver', 'FUNC_14': 'createData', 'VAR_21': 'user', 'VAR_22': 'check', 'VAR_23': 'list', 'CLASS_2': 'Object', 'VAR_24': 'sys_c', 'FUNC_15': 'setWtname', 'FUNC_16': 'setSysstatus', 'FUNC_17': 'setSysmuser', 'FUNC_18': 'getSuaccount', 'FUNC_19': 'setSyscuser', 'CLASS_3': 'Exception', 'VAR_25': 'e', 'FUNC_20': 'save_asData', 'FUNC_21': 'updateData', 'FUNC_22': 'setWtid', 'FUNC_23': 'length', 'FUNC_24': 'deleteByWtid'} | java | OOP | 13.16% |
/*
* Opens a WebView to see the specifications of SLOGO commands
*/
public class HelpBrowser {
private Stage myStage;
private Scene scene;
private WebView browser;
public HelpBrowser() {
myStage = new Stage();
Group helpRoot = new Group();
scene = new Scene(helpRoot, UIConstants.WIDTH, UIConstants.HEIGHT);
browser = new WebView();
helpRoot.getChildren().add(browser);
}
public void execute() {
myStage.setScene(scene);
browser.setPrefSize(UIConstants.WIDTH, UIConstants.HEIGHT);
browser.getEngine().load(DemoWSpace.class.getResource("/references/help.html").toExternalForm());
myStage.show();
}
} | /*
* Opens a WebView to see the specifications of SLOGO commands
*/
public class CLASS_0 {
private CLASS_1 VAR_0;
private CLASS_2 VAR_1;
private CLASS_3 VAR_2;
public CLASS_0() {
VAR_0 = new CLASS_1();
Group helpRoot = new Group();
VAR_1 = new CLASS_2(helpRoot, UIConstants.VAR_3, UIConstants.HEIGHT);
VAR_2 = new CLASS_3();
helpRoot.FUNC_0().FUNC_1(VAR_2);
}
public void FUNC_2() {
VAR_0.setScene(VAR_1);
VAR_2.FUNC_3(UIConstants.VAR_3, UIConstants.HEIGHT);
VAR_2.FUNC_4().FUNC_5(CLASS_4.class.FUNC_6("/references/help.html").FUNC_7());
VAR_0.FUNC_8();
}
} | 0.876646 | {'CLASS_0': 'HelpBrowser', 'CLASS_1': 'Stage', 'VAR_0': 'myStage', 'CLASS_2': 'Scene', 'VAR_1': 'scene', 'CLASS_3': 'WebView', 'VAR_2': 'browser', 'VAR_3': 'WIDTH', 'FUNC_0': 'getChildren', 'FUNC_1': 'add', 'FUNC_2': 'execute', 'FUNC_3': 'setPrefSize', 'FUNC_4': 'getEngine', 'FUNC_5': 'load', 'CLASS_4': 'DemoWSpace', 'FUNC_6': 'getResource', 'FUNC_7': 'toExternalForm', 'FUNC_8': 'show'} | java | OOP | 87.38% |
/**
* Object property accessor for string properties. The "object" in {@link ObjectPropertyAccessor}
* stands for the assignment of property directly to one object. In database you can see only one
* foreign key relation of property table.
*
* @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a>
*
* @param <O>
* the object having the properties
* @param <P>
* the type of property to handle
*/
public abstract class ObjectPropertyAccessor<O extends Propertyable, P extends StringProperty>
extends StringPropertyAccessor<O, P> {
/**
*
* @param eventDispatcher
* the event dispatcher for dispatching event on property changes
*/
public ObjectPropertyAccessor(EventDispatcher eventDispatcher) {
super(eventDispatcher);
}
/**
* Get an global property, that is one with no key group (internal the key group will be global
* however).
*
* @param object
* the object to get the property of
* @param keyGroup
* the key group of the property to get
* @param key
* the key of the property
* @return the property or null if the property does not exists
* @throws AuthorizationException
* Thrown, when the user is not allowed to access.
*/
@Override
protected P handleGetObjectPropertyUnfiltered(O object, String keyGroup, String key)
throws AuthorizationException {
for (StringProperty property : object.getProperties()) {
if (property.keyEquals(keyGroup, key)) {
return (P) property;
}
}
return null;
}
/**
* Removes the property of an object
*
* @param object
* object to get the property of
* @param keyGroup
* the key group of the property to get
* @param key
* the key of the property
* @throws AuthorizationException
* Thrown, when the user is not allowed to access.
*/
@Override
protected void handleRemoveObjectProperty(O object, String keyGroup, String key)
throws AuthorizationException {
P property = handleGetObjectPropertyUnfiltered(object, keyGroup, key);
if (property != null) {
object.getProperties().remove(property);
PropertyDao propertyDao = ServiceLocator.findService(PropertyDao.class);
propertyDao.remove(property);
}
}
} | /**
* Object property accessor for string properties. The "object" in {@link ObjectPropertyAccessor}
* stands for the assignment of property directly to one object. In database you can see only one
* foreign key relation of property table.
*
* @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a>
*
* @param <O>
* the object having the properties
* @param <P>
* the type of property to handle
*/
public abstract class CLASS_0<CLASS_1 extends CLASS_2, CLASS_3 extends CLASS_4>
extends CLASS_5<CLASS_1, CLASS_3> {
/**
*
* @param eventDispatcher
* the event dispatcher for dispatching event on property changes
*/
public CLASS_0(CLASS_6 eventDispatcher) {
super(eventDispatcher);
}
/**
* Get an global property, that is one with no key group (internal the key group will be global
* however).
*
* @param object
* the object to get the property of
* @param keyGroup
* the key group of the property to get
* @param key
* the key of the property
* @return the property or null if the property does not exists
* @throws AuthorizationException
* Thrown, when the user is not allowed to access.
*/
@VAR_0
protected CLASS_3 FUNC_0(CLASS_1 VAR_1, String VAR_2, String VAR_3)
throws AuthorizationException {
for (CLASS_4 VAR_4 : VAR_1.FUNC_1()) {
if (VAR_4.FUNC_2(VAR_2, VAR_3)) {
return (CLASS_3) VAR_4;
}
}
return null;
}
/**
* Removes the property of an object
*
* @param object
* object to get the property of
* @param keyGroup
* the key group of the property to get
* @param key
* the key of the property
* @throws AuthorizationException
* Thrown, when the user is not allowed to access.
*/
@VAR_0
protected void FUNC_3(CLASS_1 VAR_1, String VAR_2, String VAR_3)
throws AuthorizationException {
CLASS_3 VAR_4 = FUNC_0(VAR_1, VAR_2, VAR_3);
if (VAR_4 != null) {
VAR_1.FUNC_1().FUNC_4(VAR_4);
CLASS_7 propertyDao = VAR_5.FUNC_5(CLASS_7.class);
propertyDao.FUNC_4(VAR_4);
}
}
} | 0.720933 | {'CLASS_0': 'ObjectPropertyAccessor', 'CLASS_1': 'O', 'CLASS_2': 'Propertyable', 'CLASS_3': 'P', 'CLASS_4': 'StringProperty', 'CLASS_5': 'StringPropertyAccessor', 'CLASS_6': 'EventDispatcher', 'VAR_0': 'Override', 'FUNC_0': 'handleGetObjectPropertyUnfiltered', 'VAR_1': 'object', 'VAR_2': 'keyGroup', 'VAR_3': 'key', 'VAR_4': 'property', 'FUNC_1': 'getProperties', 'FUNC_2': 'keyEquals', 'FUNC_3': 'handleRemoveObjectProperty', 'FUNC_4': 'remove', 'CLASS_7': 'PropertyDao', 'VAR_5': 'ServiceLocator', 'FUNC_5': 'findService'} | java | Texto | 2.93% |
package com.winterchen.common.exception;
import org.springframework.util.StringUtils;
/**
* @author winterchen
* @version 1.0
* @date 2021/1/19 1:03 下午
* @description 数据重复异常
**/
public class DataExistException extends RuntimeException{
public DataExistException(Class clazz, String field, String val) {
super(DataExistException.generateMessage(clazz.getSimpleName(), field, val));
}
public DataExistException(Class clazz) {
super(DataExistException.generateMessage(clazz.getSimpleName()));
}
private static String generateMessage(String entity, String field, String val) {
return StringUtils.capitalize(entity)
+ " with " + field + " "+ val + " existed";
}
private static String generateMessage(String entity) {
return StringUtils.capitalize(entity)
+ " is existed";
}
}
| package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3;
import IMPORT_4.IMPORT_5.IMPORT_6.IMPORT_7;
/**
* @author winterchen
* @version 1.0
* @date 2021/1/19 1:03 下午
* @description 数据重复异常
**/
public class CLASS_0 extends CLASS_1{
public CLASS_0(CLASS_2 VAR_1, CLASS_3 VAR_2, CLASS_3 VAR_3) {
super(VAR_0.FUNC_0(VAR_1.FUNC_1(), VAR_2, VAR_3));
}
public CLASS_0(CLASS_2 VAR_1) {
super(VAR_0.FUNC_0(VAR_1.FUNC_1()));
}
private static CLASS_3 FUNC_0(CLASS_3 VAR_4, CLASS_3 VAR_2, CLASS_3 VAR_3) {
return IMPORT_7.FUNC_2(VAR_4)
+ " with " + VAR_2 + " "+ VAR_3 + " existed";
}
private static CLASS_3 FUNC_0(CLASS_3 VAR_4) {
return IMPORT_7.FUNC_2(VAR_4)
+ " is existed";
}
}
| 0.967938 | {'IMPORT_0': 'com', 'IMPORT_1': 'winterchen', 'IMPORT_2': 'common', 'IMPORT_3': 'exception', 'IMPORT_4': 'org', 'IMPORT_5': 'springframework', 'IMPORT_6': 'util', 'IMPORT_7': 'StringUtils', 'CLASS_0': 'DataExistException', 'VAR_0': 'DataExistException', 'CLASS_1': 'RuntimeException', 'CLASS_2': 'Class', 'VAR_1': 'clazz', 'CLASS_3': 'String', 'VAR_2': 'field', 'VAR_3': 'val', 'FUNC_0': 'generateMessage', 'FUNC_1': 'getSimpleName', 'VAR_4': 'entity', 'FUNC_2': 'capitalize'} | java | OOP | 35.58% |
package Surabhi.FreshWorks.service;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.TimerTask;
import org.json.simple.JSONObject;
public class scheduler extends TimerTask{
//private Thread t;
private String file = null;
public scheduler(String file){
this.file=file;
}
public void run() {
serviceImpl srv = new serviceImpl();
try {
JSONObject data = srv.getRecord(file);
for(Object key : data.keySet()) {
JSONObject prodObject = (JSONObject)data.get(key);
if(prodObject.get("TTL") != null) {
JSONObject prod = (JSONObject)prodObject.get("TTL");
Long seconds = (Long) prod.get("seconds");
LocalDateTime saveingtime = LocalDateTime.parse((CharSequence) prod.get("Savingtime"));
LocalDateTime instant = LocalDateTime.now();
Duration duration = Duration.between(saveingtime, instant);
if(duration.getSeconds()>=seconds) {
if(data.get(key)!=null) {
data.remove(key);
srv.writeRecord(file, data);
System.out.println("Key Timeout: "+key);
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| package Surabhi.FreshWorks.service;
import java.io.IOException;
import java.IMPORT_0.Duration;
import java.IMPORT_0.LocalDateTime;
import java.util.TimerTask;
import org.json.simple.JSONObject;
public class scheduler extends TimerTask{
//private Thread t;
private String file = null;
public scheduler(String file){
this.file=file;
}
public void run() {
serviceImpl srv = new serviceImpl();
try {
JSONObject VAR_0 = srv.getRecord(file);
for(Object key : VAR_0.keySet()) {
JSONObject prodObject = (JSONObject)VAR_0.get(key);
if(prodObject.get("TTL") != null) {
JSONObject prod = (JSONObject)prodObject.get("TTL");
Long seconds = (Long) prod.get("seconds");
LocalDateTime saveingtime = LocalDateTime.FUNC_0((CharSequence) prod.get("Savingtime"));
LocalDateTime instant = LocalDateTime.now();
Duration duration = Duration.between(saveingtime, instant);
if(duration.getSeconds()>=seconds) {
if(VAR_0.get(key)!=null) {
VAR_0.remove(key);
srv.writeRecord(file, VAR_0);
System.out.println("Key Timeout: "+key);
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 0.056876 | {'IMPORT_0': 'time', 'VAR_0': 'data', 'FUNC_0': 'parse'} | java | OOP | 37.93% |
// Accept all directories and dome model files
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
boolean bRet = f.getName().endsWith(".xls") || f.getName().endsWith(".xlsx");
Debug.trace(Debug.ALL, "excelFiler" + bRet);
return (f.getName().endsWith(".xls") || f.getName().endsWith(".xlsx"));
} | // Accept all directories and dome model files
public boolean accept(File f) {
if (f.FUNC_0()) {
return true;
}
boolean bRet = f.getName().FUNC_1(".xls") || f.getName().FUNC_1(".xlsx");
Debug.FUNC_2(Debug.ALL, "excelFiler" + bRet);
return (f.getName().FUNC_1(".xls") || f.getName().FUNC_1(".xlsx"));
} | 0.164639 | {'FUNC_0': 'isDirectory', 'FUNC_1': 'endsWith', 'FUNC_2': 'trace'} | java | Procedural | 29.85% |
/**
* The bank account associated with this transaction.
*/
public final class TransactionBank
{
private String code;
private String iban;
/**
* The bank identified by a bank code.
**/
public String getCode()
{
return code;
}
public TransactionBank setCode( String code )
{
this.code = code;
return this;
}
/**
* The international bank account number.
**/
public String getIban()
{
return iban;
}
public TransactionBank setIban( String iban )
{
this.iban = iban;
return this;
}
} | /**
* The bank account associated with this transaction.
*/
public final class CLASS_0
{
private CLASS_1 VAR_0;
private CLASS_1 VAR_1;
/**
* The bank identified by a bank code.
**/
public CLASS_1 FUNC_0()
{
return VAR_0;
}
public CLASS_0 FUNC_1( CLASS_1 VAR_0 )
{
this.VAR_0 = VAR_0;
return this;
}
/**
* The international bank account number.
**/
public CLASS_1 FUNC_2()
{
return VAR_1;
}
public CLASS_0 FUNC_3( CLASS_1 VAR_1 )
{
this.VAR_1 = VAR_1;
return this;
}
} | 0.999168 | {'CLASS_0': 'TransactionBank', 'CLASS_1': 'String', 'VAR_0': 'code', 'VAR_1': 'iban', 'FUNC_0': 'getCode', 'FUNC_1': 'setCode', 'FUNC_2': 'getIban', 'FUNC_3': 'setIban'} | java | OOP | 100.00% |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.usermodel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import junit.framework.TestCase;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.util.TempFile;
/**
* @author <NAME> (acoliver at apache dot org)
* @author <NAME>
*/
public class TestFormulas
extends TestCase {
public TestFormulas(String s) {
super(s);
}
/**
* Add 1+1 -- WHoohoo!
*/
public void testBasicAddIntegers()
throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormula",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
//get our minimum values
r = s.createRow((short)1);
c = r.createCell((short)1);
c.setCellFormula(1 + "+" + 1);
wb.write(out);
out.close();
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0);
r = s.getRow((short)1);
c = r.getCell((short)1);
assertTrue("Formula is as expected",("1+1".equals(c.getCellFormula())));
in.close();
}
/**
* Add various integers
*/
public void testAddIntegers()
throws Exception {
binomialOperator("+");
}
/**
* Multiply various integers
*/
public void testMultplyIntegers()
throws Exception {
binomialOperator("*");
}
/**
* Subtract various integers
*/
public void testSubtractIntegers()
throws Exception {
binomialOperator("-");
}
/**
* Subtract various integers
*/
public void testDivideIntegers()
throws Exception {
binomialOperator("/");
}
/**
* Exponentialize various integers;
*/
public void testPowerIntegers()
throws Exception {
binomialOperator("^");
}
/**
* Concatinate two numbers 1&2 = 12
*/
public void testConcatIntegers()
throws Exception {
binomialOperator("&");
}
/**
* tests 1*2+3*4
*/
public void testOrderOfOperationsMultiply()
throws Exception {
orderTest("1*2+3*4");
}
/**
* tests 1*2+3^4
*/
public void testOrderOfOperationsPower()
throws Exception {
orderTest("1*2+3^4");
}
/**
* Tests that parenthesis are obeyed
*/
public void testParenthesis()
throws Exception {
orderTest("(1*3)+2+(1+2)*(3^4)^5");
}
public void testReferencesOpr()
throws Exception {
String[] operation = new String[] {
"+", "-", "*", "/", "^", "&"
};
for (int k = 0; k < operation.length; k++) {
operationRefTest(operation[k]);
}
}
/**
* Tests creating a file with floating point in a formula.
*
*/
public void testFloat()
throws Exception {
floatTest("*");
floatTest("/");
}
private void floatTest(String operator)
throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormulaFloat",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
//get our minimum values
r = s.createRow((short)0);
c = r.createCell((short)1);
c.setCellFormula(""+Float.MIN_VALUE + operator + Float.MIN_VALUE);
for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2) ) {
r = s.createRow((short) x);
for (short y = 1; y < 256 && y > 0; y= (short) (y +2)) {
c = r.createCell((short) y);
c.setCellFormula("" + x+"."+y + operator + y +"."+x);
}
}
if (s.getLastRowNum() < Short.MAX_VALUE) {
r = s.createRow((short)0);
c = r.createCell((short)0);
c.setCellFormula("" + Float.MAX_VALUE + operator + Float.MAX_VALUE);
}
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
out=null;wb=null; //otherwise we get out of memory error!
floatVerify(operator,file);
}
private void floatVerify(String operator, File file)
throws Exception {
short rownum = 0;
FileInputStream in = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(in);
HSSFSheet s = wb.getSheetAt(0);
HSSFRow r = null;
HSSFCell c = null;
// dont know how to check correct result .. for the moment, we just verify that the file can be read.
for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) {
r = s.getRow((short) x);
for (short y = 1; y < 256 && y > 0; y=(short)(y+2)) {
c = r.getCell((short) y);
assertTrue("got a formula",c.getCellFormula()!=null);
assertTrue("loop Formula is as expected "+x+"."+y+operator+y+"."+x+"!="+c.getCellFormula(),(
(""+x+"."+y+operator+y+"."+x).equals(c.getCellFormula()) ));
}
}
in.close();
assertTrue("file exists",file.exists());
}
public void testAreaSum()
throws Exception {
areaFunctionTest("SUM");
}
public void testAreaAverage()
throws Exception {
areaFunctionTest("AVERAGE");
}
public void testRefArraySum()
throws Exception {
refArrayFunctionTest("SUM");
}
public void testAreaArraySum()
throws Exception {
refAreaArrayFunctionTest("SUM");
}
private void operationRefTest(String operator)
throws Exception {
File file = TempFile.createTempFile("testFormula",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
//get our minimum values
r = s.createRow((short)0);
c = r.createCell((short)1);
c.setCellFormula("A2" + operator + "A3");
for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) {
r = s.createRow((short) x);
for (short y = 1; y < 256 && y > 0; y++) {
String ref=null;
String ref2=null;
short refx1=0;
short refy1=0;
short refx2=0;
short refy2=0;
if (x +50 < Short.MAX_VALUE) {
refx1=(short)(x+50);
refx2=(short)(x+46);
} else {
refx1=(short)(x-4);
refx2=(short)(x-3);
}
if (y+50 < 255) {
refy1=(short)(y+50);
refy2=(short)(y+49);
} else {
refy1=(short)(y-4);
refy2=(short)(y-3);
}
c = r.getCell((short) y);
CellReference cr= new CellReference(refx1,refy1);
ref=cr.toString();
cr=new CellReference(refx2,refy2);
ref2=cr.toString();
c = r.createCell((short) y);
c.setCellFormula("" + ref + operator + ref2);
}
}
//make sure we do the maximum value of the Int operator
if (s.getLastRowNum() < Short.MAX_VALUE) {
r = s.createRow((short)0);
c = r.createCell((short)0);
c.setCellFormula("" + "B1" + operator + "IV255");
}
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
operationalRefVerify(operator,file);
}
/**
* Opens the sheet we wrote out by binomialOperator and makes sure the formulas
* all match what we expect (x operator y)
*/
private void operationalRefVerify(String operator, File file)
throws Exception {
short rownum = 0;
FileInputStream in = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(in);
HSSFSheet s = wb.getSheetAt(0);
HSSFRow r = null;
HSSFCell c = null;
//get our minimum values
r = s.getRow((short)0);
c = r.getCell((short)1);
//get our minimum values
assertTrue("minval Formula is as expected A2"+operator+"A3 != "+c.getCellFormula(),
( ("A2"+operator+"A3").equals(c.getCellFormula())
));
for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) {
r = s.getRow((short) x);
for (short y = 1; y < 256 && y > 0; y++) {
String ref=null;
String ref2=null;
short refx1=0;
short refy1=0;
short refx2=0;
short refy2=0;
if (x +50 < Short.MAX_VALUE) {
refx1=(short)(x+50);
refx2=(short)(x+46);
} else {
refx1=(short)(x-4);
refx2=(short)(x-3);
}
if (y+50 < 255) {
refy1=(short)(y+50);
refy2=(short)(y+49);
} else {
refy1=(short)(y-4);
refy2=(short)(y-3);
}
c = r.getCell((short) y);
CellReference cr= new CellReference(refx1,refy1);
ref=cr.toString();
cr=new CellReference(refx2,refy2);
ref2=cr.toString();
assertTrue("loop Formula is as expected "+ref+operator+ref2+"!="+c.getCellFormula(),(
(""+ref+operator+ref2).equals(c.getCellFormula())
)
);
}
}
//test our maximum values
r = s.getRow((short)0);
c = r.getCell((short)0);
assertTrue("maxval Formula is as expected",(
("B1"+operator+"IV255").equals(c.getCellFormula())
)
);
in.close();
assertTrue("file exists",file.exists());
}
/**
* tests order wrting out == order writing in for a given formula
*/
private void orderTest(String formula)
throws Exception {
File file = TempFile.createTempFile("testFormula",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
//get our minimum values
r = s.createRow((short)0);
c = r.createCell((short)1);
c.setCellFormula(formula);
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0);
//get our minimum values
r = s.getRow((short)0);
c = r.getCell((short)1);
assertTrue("minval Formula is as expected",
formula.equals(c.getCellFormula())
);
in.close();
}
/**
* All multi-binomial operator tests use this to create a worksheet with a
* huge set of x operator y formulas. Next we call binomialVerify and verify
* that they are all how we expect.
*/
private void binomialOperator(String operator)
throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormula",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
//get our minimum values
r = s.createRow((short)0);
c = r.createCell((short)1);
c.setCellFormula(1 + operator + 1);
for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) {
r = s.createRow((short) x);
for (short y = 1; y < 256 && y > 0; y++) {
c = r.createCell((short) y);
c.setCellFormula("" + x + operator + y);
}
}
//make sure we do the maximum value of the Int operator
if (s.getLastRowNum() < Short.MAX_VALUE) {
r = s.createRow((short)0);
c = r.createCell((short)0);
c.setCellFormula("" + Short.MAX_VALUE + operator + Short.MAX_VALUE);
}
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
binomialVerify(operator,file);
}
/**
* Opens the sheet we wrote out by binomialOperator and makes sure the formulas
* all match what we expect (x operator y)
*/
private void binomialVerify(String operator, File file)
throws Exception {
short rownum = 0;
FileInputStream in = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(in);
HSSFSheet s = wb.getSheetAt(0);
HSSFRow r = null;
HSSFCell c = null;
//get our minimum values
r = s.getRow((short)0);
c = r.getCell((short)1);
assertTrue("minval Formula is as expected 1"+operator+"1 != "+c.getCellFormula(),
( ("1"+operator+"1").equals(c.getCellFormula())
));
for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) {
r = s.getRow((short) x);
for (short y = 1; y < 256 && y > 0; y++) {
c = r.getCell((short) y);
assertTrue("loop Formula is as expected "+x+operator+y+"!="+c.getCellFormula(),(
(""+x+operator+y).equals(c.getCellFormula())
)
);
}
}
//test our maximum values
r = s.getRow((short)0);
c = r.getCell((short)0);
assertTrue("maxval Formula is as expected",(
(""+Short.MAX_VALUE+operator+Short.MAX_VALUE).equals(c.getCellFormula())
)
);
in.close();
assertTrue("file exists",file.exists());
}
/**
* Writes a function then tests to see if its correct
*
*/
public void areaFunctionTest(String function)
throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormulaAreaFunction"+function,".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
r = s.createRow((short) 0);
c = r.createCell((short) 0);
c.setCellFormula(function+"(A2:A3)");
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0);
r = s.getRow(0);
c = r.getCell((short)0);
assertTrue("function ="+function+"(A2:A3)",
( (function+"(A2:A3)").equals((function+"(A2:A3)")) )
);
in.close();
}
/**
* Writes a function then tests to see if its correct
*
*/
public void refArrayFunctionTest(String function)
throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormulaArrayFunction"+function,".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
r = s.createRow((short) 0);
c = r.createCell((short) 0);
c.setCellFormula(function+"(A2,A3)");
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0);
r = s.getRow(0);
c = r.getCell((short)0);
assertTrue("function ="+function+"(A2,A3)",
( (function+"(A2,A3)").equals(c.getCellFormula()) )
);
in.close();
}
/**
* Writes a function then tests to see if its correct
*
*/
public void refAreaArrayFunctionTest(String function)
throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormulaAreaArrayFunction"+function,".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
r = s.createRow((short) 0);
c = r.createCell((short) 0);
c.setCellFormula(function+"(A2:A4,B2:B4)");
c=r.createCell((short) 1);
c.setCellFormula(function+"($A$2:$A4,B$2:B4)");
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0);
r = s.getRow(0);
c = r.getCell((short)0);
assertTrue("function ="+function+"(A2:A4,B2:B4)",
( (function+"(A2:A4,B2:B4)").equals(c.getCellFormula()) )
);
c=r.getCell((short) 1);
assertTrue("function ="+function+"($A$2:$A4,B$2:B4)",
( (function+"($A$2:$A4,B$2:B4)").equals(c.getCellFormula()) )
);
in.close();
}
public void testAbsRefs() throws Exception {
File file = TempFile.createTempFile("testFormulaAbsRef",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
r = s.createRow((short) 0);
c = r.createCell((short) 0);
c.setCellFormula("A3+A2");
c=r.createCell( (short) 1);
c.setCellFormula("$A3+$A2");
c=r.createCell( (short) 2);
c.setCellFormula("A$3+A$2");
c=r.createCell( (short) 3);
c.setCellFormula("$A$3+$A$2");
c=r.createCell( (short) 4);
c.setCellFormula("SUM($A$3,$A$2)");
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0);
r = s.getRow(0);
c = r.getCell((short)0);
assertTrue("A3+A2", ("A3+A2").equals(c.getCellFormula()));
c = r.getCell((short)1);
assertTrue("$A3+$A2", ("$A3+$A2").equals(c.getCellFormula()));
c = r.getCell((short)2);
assertTrue("A$3+A$2", ("A$3+A$2").equals(c.getCellFormula()));
c = r.getCell((short)3);
assertTrue("$A$3+$A$2", ("$A$3+$A$2").equals(c.getCellFormula()));
c = r.getCell((short)4);
assertTrue("SUM($A$3,$A$2)", ("SUM($A$3,$A$2)").equals(c.getCellFormula()));
in.close();
}
public void testSheetFunctions()
throws IOException
{
String filename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testSheetFormula",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("A");
HSSFRow r = null;
HSSFCell c = null;
r = s.createRow((short)0);
c = r.createCell((short)0);c.setCellValue(1);
c = r.createCell((short)1);c.setCellValue(2);
s = wb.createSheet("B");
r = s.createRow((short)0);
c=r.createCell((short)0); c.setCellFormula("AVERAGE(A!A1:B1)");
c=r.createCell((short)1); c.setCellFormula("A!A1+A!B1");
c=r.createCell((short)2); c.setCellFormula("A!$A$1+A!$B1");
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheet("B");
r = s.getRow(0);
c = r.getCell((short)0);
assertTrue("expected: AVERAGE(A!A1:B1) got: "+c.getCellFormula(), ("AVERAGE(A!A1:B1)").equals(c.getCellFormula()));
c = r.getCell((short)1);
assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula()));
in.close();
}
public void testRVAoperands() throws Exception {
File file = TempFile.createTempFile("testFormulaRVA",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
r = s.createRow((short) 0);
c = r.createCell((short) 0);
c.setCellFormula("A3+A2");
c=r.createCell( (short) 1);
c.setCellFormula("AVERAGE(A3,A2)");
c=r.createCell( (short) 2);
c.setCellFormula("ROW(A3)");
c=r.createCell( (short) 3);
c.setCellFormula("AVERAGE(A2:A3)");
c=r.createCell( (short) 4);
c.setCellFormula("POWER(A2,A3)");
c=r.createCell( (short) 5);
c.setCellFormula("SIN(A2)");
c=r.createCell( (short) 6);
c.setCellFormula("SUM(A2:A3)");
c=r.createCell( (short) 7);
c.setCellFormula("SUM(A2,A3)");
r = s.createRow((short) 1);c=r.createCell( (short) 0); c.setCellValue(2.0);
r = s.createRow((short) 2);c=r.createCell( (short) 0); c.setCellValue(3.0);
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
}
public void testStringFormulas()
throws IOException
{
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testStringFormula",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("A");
HSSFRow r = null;
HSSFCell c = null;
r = s.createRow((short)0);
c=r.createCell((short)1); c.setCellFormula("UPPER(\"abc\")");
c=r.createCell((short)2); c.setCellFormula("LOWER(\"ABC\")");
c=r.createCell((short)3); c.setCellFormula("CONCATENATE(\" my \",\" name \")");
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(readFilename+File.separator+"StringFormulas.xls");
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0);
r = s.getRow(0);
c = r.getCell((short)0);
assertTrue("expected: UPPER(\"xyz\") got "+c.getCellFormula(), ("UPPER(\"xyz\")").equals(c.getCellFormula()));
//c = r.getCell((short)1);
//assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula()));
in.close();
}
public void testLogicalFormulas()
throws IOException
{
File file = TempFile.createTempFile("testLogicalFormula",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("A");
HSSFRow r = null;
HSSFCell c = null;
r = s.createRow((short)0);
c=r.createCell((short)1); c.setCellFormula("IF(A1<A2,B1,B2)");
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0);
r = s.getRow(0);
c = r.getCell((short)1);
assertEquals("Formula in cell 1 ","IF(A1<A2,B1,B2)",c.getCellFormula());
in.close();
}
public void testDateFormulas()
throws IOException
{
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testDateFormula",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("testSheet1");
HSSFRow r = null;
HSSFCell c = null;
r = s.createRow( (short)0 );
c = r.createCell( (short)0 );
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
c.setCellValue(new Date());
c.setCellStyle(cellStyle);
// assertEquals("Checking hour = " + hour, date.getTime().getTime(),
// HSSFDateUtil.getJavaDate(excelDate).getTime());
for (int k=1; k < 100; k++) {
r=s.createRow((short)k);
c=r.createCell((short)0);
c.setCellFormula("A"+(k)+"+1");
c.setCellStyle(cellStyle);
}
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
}
public void testIfFormulas()
throws IOException
{
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testIfFormula",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("testSheet1");
HSSFRow r = null;
HSSFCell c = null;
r = s.createRow((short)0);
c=r.createCell((short)1); c.setCellValue(1);
c=r.createCell((short)2); c.setCellValue(2);
c=r.createCell((short)3); c.setCellFormula("MAX(A1:B1)");
c=r.createCell((short)4); c.setCellFormula("IF(A1=D1,\"A1\",\"B1\")");
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0);
r = s.getRow(0);
c = r.getCell((short)4);
assertTrue("expected: IF(A1=D1,\"A1\",\"B1\") got "+c.getCellFormula(), ("IF(A1=D1,\"A1\",\"B1\")").equals(c.getCellFormula()));
in.close();
in = new FileInputStream(readFilename+File.separator+"IfFormulaTest.xls");
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0);
r = s.getRow(3);
c = r.getCell((short)0);
assertTrue("expected: IF(A3=A1,\"A1\",\"A2\") got "+c.getCellFormula(), ("IF(A3=A1,\"A1\",\"A2\")").equals(c.getCellFormula()));
//c = r.getCell((short)1);
//assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula()));
in.close();
File simpleIf = TempFile.createTempFile("testSimpleIfFormulaWrite",".xls");
out = new FileOutputStream(simpleIf);
wb = new HSSFWorkbook();
s = wb.createSheet("testSheet1");
r = null;
c = null;
r = s.createRow((short)0);
c=r.createCell((short)0); c.setCellFormula("IF(1=1,0,1)");
wb.write(out);
out.close();
assertTrue("file exists", simpleIf.exists());
assertTrue("length of simpleIf file is zero", (simpleIf.length()>0));
File nestedIf = TempFile.createTempFile("testNestedIfFormula",".xls");
out = new FileOutputStream(nestedIf);
wb = new HSSFWorkbook();
s = wb.createSheet("testSheet1");
r = null;
c = null;
r = s.createRow((short)0);
c=r.createCell((short)0);
c.setCellValue(1);
c=r.createCell((short)1);
c.setCellValue(3);
HSSFCell formulaCell=r.createCell((short)3);
r = s.createRow((short)1);
c=r.createCell((short)0);
c.setCellValue(3);
c=r.createCell((short)1);
c.setCellValue(7);
formulaCell.setCellFormula("IF(A1=B1,AVERAGE(A1:B1),AVERAGE(A2:B2))");
wb.write(out);
out.close();
assertTrue("file exists", nestedIf.exists());
assertTrue("length of nestedIf file is zero", (nestedIf.length()>0));
}
public void testSumIf()
throws IOException
{
String readFilename = System.getProperty("HSSF.testdata.path");
String function ="SUMIF(A1:A5,\">4000\",B1:B5)";
File inFile = new File(readFilename+"/sumifformula.xls");
FileInputStream in = new FileInputStream(inFile);
HSSFWorkbook wb = new HSSFWorkbook(in);
in.close();
HSSFSheet s = wb.getSheetAt(0);
HSSFRow r = s.getRow(0);
HSSFCell c = r.getCell((short)2);
assertEquals(function, c.getCellFormula());
File file = TempFile.createTempFile("testSumIfFormula",".xls");
FileOutputStream out = new FileOutputStream(file);
wb = new HSSFWorkbook();
s = wb.createSheet();
r = s.createRow((short)0);
c=r.createCell((short)0); c.setCellValue((double)1000);
c=r.createCell((short)1); c.setCellValue((double)1);
r = s.createRow((short)1);
c=r.createCell((short)0); c.setCellValue((double)2000);
c=r.createCell((short)1); c.setCellValue((double)2);
r = s.createRow((short)2);
c=r.createCell((short)0); c.setCellValue((double)3000);
c=r.createCell((short)1); c.setCellValue((double)3);
r = s.createRow((short)3);
c=r.createCell((short)0); c.setCellValue((double)4000);
c=r.createCell((short)1); c.setCellValue((double)4);
r = s.createRow((short)4);
c=r.createCell((short)0); c.setCellValue((double)5000);
c=r.createCell((short)1); c.setCellValue((double)5);
r = s.getRow(0);
c=r.createCell((short)2); c.setCellFormula(function);
wb.write(out);
out.close();
assertTrue("sumif file doesnt exists", (file.exists()));
assertTrue("sumif == 0 bytes", file.length() > 0);
}
public void testSquareMacro() throws IOException {
File dir = new File(System.getProperty("HSSF.testdata.path"));
File xls = new File(dir, "SquareMacro.xls");
FileInputStream in = new FileInputStream(xls);
HSSFWorkbook w;
try {
w = new HSSFWorkbook(in);
} finally {
in.close();
}
HSSFSheet s0 = w.getSheetAt(0);
HSSFRow[] r = {s0.getRow(0), s0.getRow(1)};
HSSFCell a1 = r[0].getCell((short) 0);
assertEquals("square(1)", a1.getCellFormula());
assertEquals(1d, a1.getNumericCellValue(), 1e-9);
HSSFCell a2 = r[1].getCell((short) 0);
assertEquals("square(2)", a2.getCellFormula());
assertEquals(4d, a2.getNumericCellValue(), 1e-9);
HSSFCell b1 = r[0].getCell((short) 1);
assertEquals("IF(TRUE,square(1))", b1.getCellFormula());
assertEquals(1d, b1.getNumericCellValue(), 1e-9);
HSSFCell b2 = r[1].getCell((short) 1);
assertEquals("IF(TRUE,square(2))", b2.getCellFormula());
assertEquals(4d, b2.getNumericCellValue(), 1e-9);
HSSFCell c1 = r[0].getCell((short) 2);
assertEquals("square(square(1))", c1.getCellFormula());
assertEquals(1d, c1.getNumericCellValue(), 1e-9);
HSSFCell c2 = r[1].getCell((short) 2);
assertEquals("square(square(2))", c2.getCellFormula());
assertEquals(16d, c2.getNumericCellValue(), 1e-9);
HSSFCell d1 = r[0].getCell((short) 3);
assertEquals("square(one())", d1.getCellFormula());
assertEquals(1d, d1.getNumericCellValue(), 1e-9);
HSSFCell d2 = r[1].getCell((short) 3);
assertEquals("square(two())", d2.getCellFormula());
assertEquals(4d, d2.getNumericCellValue(), 1e-9);
}
public void testStringFormulaRead() throws IOException {
File dir = new File(System.getProperty("HSSF.testdata.path"));
File xls = new File(dir, "StringFormulas.xls");
FileInputStream in = new FileInputStream(xls);
HSSFWorkbook w;
try {
w = new HSSFWorkbook(in);
} finally {
in.close();
}
HSSFCell c = w.getSheetAt(0).getRow(0).getCell((short)0);
assertEquals("String Cell value","XYZ",c.getStringCellValue());
}
/** test for bug 34021*/
public void testComplexSheetRefs () throws IOException {
HSSFWorkbook sb = new HSSFWorkbook();
HSSFSheet s1 = sb.createSheet("Sheet a.1");
HSSFSheet s2 = sb.createSheet("Sheet.A");
s2.createRow(1).createCell((short) 2).setCellFormula("'Sheet a.1'!A1");
s1.createRow(1).createCell((short) 2).setCellFormula("'Sheet.A'!A1");
File file = TempFile.createTempFile("testComplexSheetRefs",".xls");
sb.write(new FileOutputStream(file));
}
/*Unknown Ptg 3C*/
public void test27272_1() throws Exception {
String readFilename = System.getProperty("HSSF.testdata.path");
File inFile = new File(readFilename+"/27272_1.xls");
FileInputStream in = new FileInputStream(inFile);
HSSFWorkbook wb = new HSSFWorkbook(in);
wb.getSheetAt(0);
assertEquals("Reference for named range ", "#REF!",wb.getNameAt(0).getReference());
File outF = File.createTempFile("bug27272_1",".xls");
wb.write(new FileOutputStream(outF));
System.out.println("Open "+outF.getAbsolutePath()+" in Excel");
}
/*Unknown Ptg 3D*/
public void test27272_2() throws Exception {
String readFilename = System.getProperty("HSSF.testdata.path");
File inFile = new File(readFilename+"/27272_2.xls");
FileInputStream in = new FileInputStream(inFile);
HSSFWorkbook wb = new HSSFWorkbook(in);
assertEquals("Reference for named range ", "#REF!",wb.getNameAt(0).getReference());
File outF = File.createTempFile("bug27272_2",".xls");
wb.write(new FileOutputStream(outF));
System.out.println("Open "+outF.getAbsolutePath()+" in Excel");
}
/* MissingArgPtg */
public void testMissingArgPtg() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell((short) 0);
cell.setCellFormula("IF(A1=\"A\",1,)");
}
public static void main(String [] args) {
System.out
.println("Testing org.apache.poi.hssf.usermodel.TestFormulas");
junit.textui.TestRunner.run(TestFormulas.class);
}
}
|
/* ====================================================================
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 IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4;
import IMPORT_5.IMPORT_6.IMPORT_7;
import IMPORT_5.IMPORT_6.IMPORT_8;
import IMPORT_5.IMPORT_6.IMPORT_9;
import IMPORT_5.IMPORT_6.IMPORT_10;
import IMPORT_5.IMPORT_11.IMPORT_12;
import IMPORT_13.IMPORT_14.IMPORT_15;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_11.IMPORT_16;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_11.IMPORT_17;
/**
* @author <NAME> (acoliver at apache dot org)
* @author <NAME>
*/
public class CLASS_0
extends IMPORT_15 {
public CLASS_0(CLASS_1 VAR_0) {
super(VAR_0);
}
/**
* Add 1+1 -- WHoohoo!
*/
public void FUNC_0()
throws CLASS_2 {
short VAR_1 = 0;
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testFormula",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2();
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
//get our minimum values
VAR_5 = VAR_0.FUNC_3((short)1);
VAR_6 = VAR_5.FUNC_4((short)1);
VAR_6.FUNC_5(1 + "+" + 1);
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_8(0);
VAR_5 = VAR_0.FUNC_9((short)1);
VAR_6 = VAR_5.FUNC_10((short)1);
FUNC_11("Formula is as expected",("1+1".FUNC_12(VAR_6.FUNC_13())));
VAR_7.FUNC_7();
}
/**
* Add various integers
*/
public void FUNC_14()
throws CLASS_2 {
FUNC_15("+");
}
/**
* Multiply various integers
*/
public void FUNC_16()
throws CLASS_2 {
FUNC_15("*");
}
/**
* Subtract various integers
*/
public void FUNC_17()
throws CLASS_2 {
FUNC_15("-");
}
/**
* Subtract various integers
*/
public void FUNC_18()
throws CLASS_2 {
FUNC_15("/");
}
/**
* Exponentialize various integers;
*/
public void FUNC_19()
throws CLASS_2 {
FUNC_15("^");
}
/**
* Concatinate two numbers 1&2 = 12
*/
public void FUNC_20()
throws CLASS_2 {
FUNC_15("&");
}
/**
* tests 1*2+3*4
*/
public void FUNC_21()
throws CLASS_2 {
FUNC_22("1*2+3*4");
}
/**
* tests 1*2+3^4
*/
public void FUNC_23()
throws CLASS_2 {
FUNC_22("1*2+3^4");
}
/**
* Tests that parenthesis are obeyed
*/
public void FUNC_24()
throws CLASS_2 {
FUNC_22("(1*3)+2+(1+2)*(3^4)^5");
}
public void FUNC_25()
throws CLASS_2 {
CLASS_1[] VAR_8 = new CLASS_1[] {
"+", "-", "*", "/", "^", "&"
};
for (int VAR_9 = 0; VAR_9 < VAR_8.VAR_10; VAR_9++) {
FUNC_27(VAR_8[VAR_9]);
}
}
/**
* Tests creating a file with floating point in a formula.
*
*/
public void FUNC_28()
throws CLASS_2 {
FUNC_29("*");
FUNC_29("/");
}
private void FUNC_29(CLASS_1 VAR_11)
throws CLASS_2 {
short VAR_1 = 0;
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testFormulaFloat",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2();
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
//get our minimum values
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6 = VAR_5.FUNC_4((short)1);
VAR_6.FUNC_5(""+VAR_12.VAR_13 + VAR_11 + VAR_12.VAR_13);
for (short VAR_14 = 1; VAR_14 < VAR_15.VAR_16 && VAR_14 > 0; VAR_14=(short)(VAR_14*2) ) {
VAR_5 = VAR_0.FUNC_3((short) VAR_14);
for (short VAR_17 = 1; VAR_17 < 256 && VAR_17 > 0; VAR_17= (short) (VAR_17 +2)) {
VAR_6 = VAR_5.FUNC_4((short) VAR_17);
VAR_6.FUNC_5("" + VAR_14+"."+VAR_17 + VAR_11 + VAR_17 +"."+VAR_14);
}
}
if (VAR_0.FUNC_30() < VAR_15.VAR_16) {
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6 = VAR_5.FUNC_4((short)0);
VAR_6.FUNC_5("" + VAR_12.VAR_16 + VAR_11 + VAR_12.VAR_16);
}
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
VAR_3=null;VAR_4=null; //otherwise we get out of memory error!
FUNC_32(VAR_11,VAR_2);
}
private void FUNC_32(CLASS_1 VAR_11, IMPORT_7 VAR_2)
throws CLASS_2 {
short VAR_1 = 0;
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
CLASS_3 VAR_4 = new CLASS_3(VAR_7);
CLASS_4 VAR_0 = VAR_4.FUNC_8(0);
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
// dont know how to check correct result .. for the moment, we just verify that the file can be read.
for (short VAR_14 = 1; VAR_14 < VAR_15.VAR_16 && VAR_14 > 0; VAR_14=(short)(VAR_14*2)) {
VAR_5 = VAR_0.FUNC_9((short) VAR_14);
for (short VAR_17 = 1; VAR_17 < 256 && VAR_17 > 0; VAR_17=(short)(VAR_17+2)) {
VAR_6 = VAR_5.FUNC_10((short) VAR_17);
FUNC_11("got a formula",VAR_6.FUNC_13()!=null);
FUNC_11("loop Formula is as expected "+VAR_14+"."+VAR_17+VAR_11+VAR_17+"."+VAR_14+"!="+VAR_6.FUNC_13(),(
(""+VAR_14+"."+VAR_17+VAR_11+VAR_17+"."+VAR_14).FUNC_12(VAR_6.FUNC_13()) ));
}
}
VAR_7.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
}
public void FUNC_33()
throws CLASS_2 {
FUNC_34("SUM");
}
public void FUNC_35()
throws CLASS_2 {
FUNC_34("AVERAGE");
}
public void FUNC_36()
throws CLASS_2 {
FUNC_37("SUM");
}
public void FUNC_38()
throws CLASS_2 {
FUNC_39("SUM");
}
private void FUNC_27(CLASS_1 VAR_11)
throws CLASS_2 {
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testFormula",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2();
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
//get our minimum values
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6 = VAR_5.FUNC_4((short)1);
VAR_6.FUNC_5("A2" + VAR_11 + "A3");
for (short VAR_14 = 1; VAR_14 < VAR_15.VAR_16 && VAR_14 > 0; VAR_14=(short)(VAR_14*2)) {
VAR_5 = VAR_0.FUNC_3((short) VAR_14);
for (short VAR_17 = 1; VAR_17 < 256 && VAR_17 > 0; VAR_17++) {
CLASS_1 VAR_18=null;
CLASS_1 VAR_19=null;
short VAR_20=0;
short VAR_21=0;
short VAR_22=0;
short VAR_23=0;
if (VAR_14 +50 < VAR_15.VAR_16) {
VAR_20=(short)(VAR_14+50);
VAR_22=(short)(VAR_14+46);
} else {
VAR_20=(short)(VAR_14-4);
VAR_22=(short)(VAR_14-3);
}
if (VAR_17+50 < 255) {
VAR_21=(short)(VAR_17+50);
VAR_23=(short)(VAR_17+49);
} else {
VAR_21=(short)(VAR_17-4);
VAR_23=(short)(VAR_17-3);
}
VAR_6 = VAR_5.FUNC_10((short) VAR_17);
IMPORT_16 VAR_24= new IMPORT_16(VAR_20,VAR_21);
VAR_18=VAR_24.FUNC_40();
VAR_24=new IMPORT_16(VAR_22,VAR_23);
VAR_19=VAR_24.FUNC_40();
VAR_6 = VAR_5.FUNC_4((short) VAR_17);
VAR_6.FUNC_5("" + VAR_18 + VAR_11 + VAR_19);
}
}
//make sure we do the maximum value of the Int operator
if (VAR_0.FUNC_30() < VAR_15.VAR_16) {
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6 = VAR_5.FUNC_4((short)0);
VAR_6.FUNC_5("" + "B1" + VAR_11 + "IV255");
}
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
FUNC_41(VAR_11,VAR_2);
}
/**
* Opens the sheet we wrote out by binomialOperator and makes sure the formulas
* all match what we expect (x operator y)
*/
private void FUNC_41(CLASS_1 VAR_11, IMPORT_7 VAR_2)
throws CLASS_2 {
short VAR_1 = 0;
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
CLASS_3 VAR_4 = new CLASS_3(VAR_7);
CLASS_4 VAR_0 = VAR_4.FUNC_8(0);
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
//get our minimum values
VAR_5 = VAR_0.FUNC_9((short)0);
VAR_6 = VAR_5.FUNC_10((short)1);
//get our minimum values
FUNC_11("minval Formula is as expected A2"+VAR_11+"A3 != "+VAR_6.FUNC_13(),
( ("A2"+VAR_11+"A3").FUNC_12(VAR_6.FUNC_13())
));
for (short VAR_14 = 1; VAR_14 < VAR_15.VAR_16 && VAR_14 > 0; VAR_14=(short)(VAR_14*2)) {
VAR_5 = VAR_0.FUNC_9((short) VAR_14);
for (short VAR_17 = 1; VAR_17 < 256 && VAR_17 > 0; VAR_17++) {
CLASS_1 VAR_18=null;
CLASS_1 VAR_19=null;
short VAR_20=0;
short VAR_21=0;
short VAR_22=0;
short VAR_23=0;
if (VAR_14 +50 < VAR_15.VAR_16) {
VAR_20=(short)(VAR_14+50);
VAR_22=(short)(VAR_14+46);
} else {
VAR_20=(short)(VAR_14-4);
VAR_22=(short)(VAR_14-3);
}
if (VAR_17+50 < 255) {
VAR_21=(short)(VAR_17+50);
VAR_23=(short)(VAR_17+49);
} else {
VAR_21=(short)(VAR_17-4);
VAR_23=(short)(VAR_17-3);
}
VAR_6 = VAR_5.FUNC_10((short) VAR_17);
IMPORT_16 VAR_24= new IMPORT_16(VAR_20,VAR_21);
VAR_18=VAR_24.FUNC_40();
VAR_24=new IMPORT_16(VAR_22,VAR_23);
VAR_19=VAR_24.FUNC_40();
FUNC_11("loop Formula is as expected "+VAR_18+VAR_11+VAR_19+"!="+VAR_6.FUNC_13(),(
(""+VAR_18+VAR_11+VAR_19).FUNC_12(VAR_6.FUNC_13())
)
);
}
}
//test our maximum values
VAR_5 = VAR_0.FUNC_9((short)0);
VAR_6 = VAR_5.FUNC_10((short)0);
FUNC_11("maxval Formula is as expected",(
("B1"+VAR_11+"IV255").FUNC_12(VAR_6.FUNC_13())
)
);
VAR_7.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
}
/**
* tests order wrting out == order writing in for a given formula
*/
private void FUNC_22(CLASS_1 VAR_25)
throws CLASS_2 {
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testFormula",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2();
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
//get our minimum values
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6 = VAR_5.FUNC_4((short)1);
VAR_6.FUNC_5(VAR_25);
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_8(0);
//get our minimum values
VAR_5 = VAR_0.FUNC_9((short)0);
VAR_6 = VAR_5.FUNC_10((short)1);
FUNC_11("minval Formula is as expected",
VAR_25.FUNC_12(VAR_6.FUNC_13())
);
VAR_7.FUNC_7();
}
/**
* All multi-binomial operator tests use this to create a worksheet with a
* huge set of x operator y formulas. Next we call binomialVerify and verify
* that they are all how we expect.
*/
private void FUNC_15(CLASS_1 VAR_11)
throws CLASS_2 {
short VAR_1 = 0;
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testFormula",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2();
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
//get our minimum values
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6 = VAR_5.FUNC_4((short)1);
VAR_6.FUNC_5(1 + VAR_11 + 1);
for (short VAR_14 = 1; VAR_14 < VAR_15.VAR_16 && VAR_14 > 0; VAR_14=(short)(VAR_14*2)) {
VAR_5 = VAR_0.FUNC_3((short) VAR_14);
for (short VAR_17 = 1; VAR_17 < 256 && VAR_17 > 0; VAR_17++) {
VAR_6 = VAR_5.FUNC_4((short) VAR_17);
VAR_6.FUNC_5("" + VAR_14 + VAR_11 + VAR_17);
}
}
//make sure we do the maximum value of the Int operator
if (VAR_0.FUNC_30() < VAR_15.VAR_16) {
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6 = VAR_5.FUNC_4((short)0);
VAR_6.FUNC_5("" + VAR_15.VAR_16 + VAR_11 + VAR_15.VAR_16);
}
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
FUNC_42(VAR_11,VAR_2);
}
/**
* Opens the sheet we wrote out by binomialOperator and makes sure the formulas
* all match what we expect (x operator y)
*/
private void FUNC_42(CLASS_1 VAR_11, IMPORT_7 VAR_2)
throws CLASS_2 {
short VAR_1 = 0;
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
CLASS_3 VAR_4 = new CLASS_3(VAR_7);
CLASS_4 VAR_0 = VAR_4.FUNC_8(0);
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
//get our minimum values
VAR_5 = VAR_0.FUNC_9((short)0);
VAR_6 = VAR_5.FUNC_10((short)1);
FUNC_11("minval Formula is as expected 1"+VAR_11+"1 != "+VAR_6.FUNC_13(),
( ("1"+VAR_11+"1").FUNC_12(VAR_6.FUNC_13())
));
for (short VAR_14 = 1; VAR_14 < VAR_15.VAR_16 && VAR_14 > 0; VAR_14=(short)(VAR_14*2)) {
VAR_5 = VAR_0.FUNC_9((short) VAR_14);
for (short VAR_17 = 1; VAR_17 < 256 && VAR_17 > 0; VAR_17++) {
VAR_6 = VAR_5.FUNC_10((short) VAR_17);
FUNC_11("loop Formula is as expected "+VAR_14+VAR_11+VAR_17+"!="+VAR_6.FUNC_13(),(
(""+VAR_14+VAR_11+VAR_17).FUNC_12(VAR_6.FUNC_13())
)
);
}
}
//test our maximum values
VAR_5 = VAR_0.FUNC_9((short)0);
VAR_6 = VAR_5.FUNC_10((short)0);
FUNC_11("maxval Formula is as expected",(
(""+VAR_15.VAR_16+VAR_11+VAR_15.VAR_16).FUNC_12(VAR_6.FUNC_13())
)
);
VAR_7.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
}
/**
* Writes a function then tests to see if its correct
*
*/
public void FUNC_34(CLASS_1 VAR_26)
throws CLASS_2 {
short VAR_1 = 0;
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testFormulaAreaFunction"+VAR_26,".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2();
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short) 0);
VAR_6 = VAR_5.FUNC_4((short) 0);
VAR_6.FUNC_5(VAR_26+"(A2:A3)");
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_8(0);
VAR_5 = VAR_0.FUNC_9(0);
VAR_6 = VAR_5.FUNC_10((short)0);
FUNC_11("function ="+VAR_26+"(A2:A3)",
( (VAR_26+"(A2:A3)").FUNC_12((VAR_26+"(A2:A3)")) )
);
VAR_7.FUNC_7();
}
/**
* Writes a function then tests to see if its correct
*
*/
public void FUNC_37(CLASS_1 VAR_26)
throws CLASS_2 {
short VAR_1 = 0;
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testFormulaArrayFunction"+VAR_26,".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2();
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short) 0);
VAR_6 = VAR_5.FUNC_4((short) 0);
VAR_6.FUNC_5(VAR_26+"(A2,A3)");
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_8(0);
VAR_5 = VAR_0.FUNC_9(0);
VAR_6 = VAR_5.FUNC_10((short)0);
FUNC_11("function ="+VAR_26+"(A2,A3)",
( (VAR_26+"(A2,A3)").FUNC_12(VAR_6.FUNC_13()) )
);
VAR_7.FUNC_7();
}
/**
* Writes a function then tests to see if its correct
*
*/
public void FUNC_39(CLASS_1 VAR_26)
throws CLASS_2 {
short VAR_1 = 0;
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testFormulaAreaArrayFunction"+VAR_26,".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2();
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short) 0);
VAR_6 = VAR_5.FUNC_4((short) 0);
VAR_6.FUNC_5(VAR_26+"(A2:A4,B2:B4)");
VAR_6=VAR_5.FUNC_4((short) 1);
VAR_6.FUNC_5(VAR_26+"($A$2:$A4,B$2:B4)");
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_8(0);
VAR_5 = VAR_0.FUNC_9(0);
VAR_6 = VAR_5.FUNC_10((short)0);
FUNC_11("function ="+VAR_26+"(A2:A4,B2:B4)",
( (VAR_26+"(A2:A4,B2:B4)").FUNC_12(VAR_6.FUNC_13()) )
);
VAR_6=VAR_5.FUNC_10((short) 1);
FUNC_11("function ="+VAR_26+"($A$2:$A4,B$2:B4)",
( (VAR_26+"($A$2:$A4,B$2:B4)").FUNC_12(VAR_6.FUNC_13()) )
);
VAR_7.FUNC_7();
}
public void FUNC_43() throws CLASS_2 {
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testFormulaAbsRef",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2();
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short) 0);
VAR_6 = VAR_5.FUNC_4((short) 0);
VAR_6.FUNC_5("A3+A2");
VAR_6=VAR_5.FUNC_4( (short) 1);
VAR_6.FUNC_5("$A3+$A2");
VAR_6=VAR_5.FUNC_4( (short) 2);
VAR_6.FUNC_5("A$3+A$2");
VAR_6=VAR_5.FUNC_4( (short) 3);
VAR_6.FUNC_5("$A$3+$A$2");
VAR_6=VAR_5.FUNC_4( (short) 4);
VAR_6.FUNC_5("SUM($A$3,$A$2)");
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_8(0);
VAR_5 = VAR_0.FUNC_9(0);
VAR_6 = VAR_5.FUNC_10((short)0);
FUNC_11("A3+A2", ("A3+A2").FUNC_12(VAR_6.FUNC_13()));
VAR_6 = VAR_5.FUNC_10((short)1);
FUNC_11("$A3+$A2", ("$A3+$A2").FUNC_12(VAR_6.FUNC_13()));
VAR_6 = VAR_5.FUNC_10((short)2);
FUNC_11("A$3+A$2", ("A$3+A$2").FUNC_12(VAR_6.FUNC_13()));
VAR_6 = VAR_5.FUNC_10((short)3);
FUNC_11("$A$3+$A$2", ("$A$3+$A$2").FUNC_12(VAR_6.FUNC_13()));
VAR_6 = VAR_5.FUNC_10((short)4);
FUNC_11("SUM($A$3,$A$2)", ("SUM($A$3,$A$2)").FUNC_12(VAR_6.FUNC_13()));
VAR_7.FUNC_7();
}
public void FUNC_44()
throws IMPORT_10
{
CLASS_1 VAR_27 = VAR_28.FUNC_45("HSSF.testdata.path");
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testSheetFormula",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2("A");
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6 = VAR_5.FUNC_4((short)0);VAR_6.FUNC_46(1);
VAR_6 = VAR_5.FUNC_4((short)1);VAR_6.FUNC_46(2);
VAR_0 = VAR_4.FUNC_2("B");
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6=VAR_5.FUNC_4((short)0); VAR_6.FUNC_5("AVERAGE(A!A1:B1)");
VAR_6=VAR_5.FUNC_4((short)1); VAR_6.FUNC_5("A!A1+A!B1");
VAR_6=VAR_5.FUNC_4((short)2); VAR_6.FUNC_5("A!$A$1+A!$B1");
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_47("B");
VAR_5 = VAR_0.FUNC_9(0);
VAR_6 = VAR_5.FUNC_10((short)0);
FUNC_11("expected: AVERAGE(A!A1:B1) got: "+VAR_6.FUNC_13(), ("AVERAGE(A!A1:B1)").FUNC_12(VAR_6.FUNC_13()));
VAR_6 = VAR_5.FUNC_10((short)1);
FUNC_11("expected: A!A1+A!B1 got: "+VAR_6.FUNC_13(), ("A!A1+A!B1").FUNC_12(VAR_6.FUNC_13()));
VAR_7.FUNC_7();
}
public void FUNC_48() throws CLASS_2 {
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testFormulaRVA",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2();
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short) 0);
VAR_6 = VAR_5.FUNC_4((short) 0);
VAR_6.FUNC_5("A3+A2");
VAR_6=VAR_5.FUNC_4( (short) 1);
VAR_6.FUNC_5("AVERAGE(A3,A2)");
VAR_6=VAR_5.FUNC_4( (short) 2);
VAR_6.FUNC_5("ROW(A3)");
VAR_6=VAR_5.FUNC_4( (short) 3);
VAR_6.FUNC_5("AVERAGE(A2:A3)");
VAR_6=VAR_5.FUNC_4( (short) 4);
VAR_6.FUNC_5("POWER(A2,A3)");
VAR_6=VAR_5.FUNC_4( (short) 5);
VAR_6.FUNC_5("SIN(A2)");
VAR_6=VAR_5.FUNC_4( (short) 6);
VAR_6.FUNC_5("SUM(A2:A3)");
VAR_6=VAR_5.FUNC_4( (short) 7);
VAR_6.FUNC_5("SUM(A2,A3)");
VAR_5 = VAR_0.FUNC_3((short) 1);VAR_6=VAR_5.FUNC_4( (short) 0); VAR_6.FUNC_46(2.0);
VAR_5 = VAR_0.FUNC_3((short) 2);VAR_6=VAR_5.FUNC_4( (short) 0); VAR_6.FUNC_46(3.0);
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
}
public void FUNC_49()
throws IMPORT_10
{
CLASS_1 VAR_29 = VAR_28.FUNC_45("HSSF.testdata.path");
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testStringFormula",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2("A");
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6=VAR_5.FUNC_4((short)1); VAR_6.FUNC_5("UPPER(\"abc\")");
VAR_6=VAR_5.FUNC_4((short)2); VAR_6.FUNC_5("LOWER(\"ABC\")");
VAR_6=VAR_5.FUNC_4((short)3); VAR_6.FUNC_5("CONCATENATE(\" my \",\" name \")");
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
IMPORT_8 VAR_7 = new IMPORT_8(VAR_29+IMPORT_7.VAR_30+"StringFormulas.xls");
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_8(0);
VAR_5 = VAR_0.FUNC_9(0);
VAR_6 = VAR_5.FUNC_10((short)0);
FUNC_11("expected: UPPER(\"xyz\") got "+VAR_6.FUNC_13(), ("UPPER(\"xyz\")").FUNC_12(VAR_6.FUNC_13()));
//c = r.getCell((short)1);
//assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula()));
VAR_7.FUNC_7();
}
public void FUNC_50()
throws IMPORT_10
{
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testLogicalFormula",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2("A");
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6=VAR_5.FUNC_4((short)1); VAR_6.FUNC_5("IF(A1<A2,B1,B2)");
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_8(0);
VAR_5 = VAR_0.FUNC_9(0);
VAR_6 = VAR_5.FUNC_10((short)1);
FUNC_51("Formula in cell 1 ","IF(A1<A2,B1,B2)",VAR_6.FUNC_13());
VAR_7.FUNC_7();
}
public void FUNC_52()
throws IMPORT_10
{
CLASS_1 VAR_29 = VAR_28.FUNC_45("HSSF.testdata.path");
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testDateFormula",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2("testSheet1");
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
VAR_5 = VAR_0.FUNC_3( (short)0 );
VAR_6 = VAR_5.FUNC_4( (short)0 );
CLASS_7 VAR_31 = VAR_4.FUNC_53();
VAR_31.FUNC_54(VAR_32.FUNC_55("m/d/yy h:mm"));
VAR_6.FUNC_46(new IMPORT_12());
VAR_6.FUNC_56(VAR_31);
// assertEquals("Checking hour = " + hour, date.getTime().getTime(),
// HSSFDateUtil.getJavaDate(excelDate).getTime());
for (int VAR_9=1; VAR_9 < 100; VAR_9++) {
VAR_5=VAR_0.FUNC_3((short)VAR_9);
VAR_6=VAR_5.FUNC_4((short)0);
VAR_6.FUNC_5("A"+(VAR_9)+"+1");
VAR_6.FUNC_56(VAR_31);
}
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
}
public void FUNC_57()
throws IMPORT_10
{
CLASS_1 VAR_29 = VAR_28.FUNC_45("HSSF.testdata.path");
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testIfFormula",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
CLASS_3 VAR_4 = new CLASS_3();
CLASS_4 VAR_0 = VAR_4.FUNC_2("testSheet1");
CLASS_5 VAR_5 = null;
CLASS_6 VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6=VAR_5.FUNC_4((short)1); VAR_6.FUNC_46(1);
VAR_6=VAR_5.FUNC_4((short)2); VAR_6.FUNC_46(2);
VAR_6=VAR_5.FUNC_4((short)3); VAR_6.FUNC_5("MAX(A1:B1)");
VAR_6=VAR_5.FUNC_4((short)4); VAR_6.FUNC_5("IF(A1=D1,\"A1\",\"B1\")");
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists",VAR_2.FUNC_31());
IMPORT_8 VAR_7 = new IMPORT_8(VAR_2);
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_8(0);
VAR_5 = VAR_0.FUNC_9(0);
VAR_6 = VAR_5.FUNC_10((short)4);
FUNC_11("expected: IF(A1=D1,\"A1\",\"B1\") got "+VAR_6.FUNC_13(), ("IF(A1=D1,\"A1\",\"B1\")").FUNC_12(VAR_6.FUNC_13()));
VAR_7.FUNC_7();
VAR_7 = new IMPORT_8(VAR_29+IMPORT_7.VAR_30+"IfFormulaTest.xls");
VAR_4 = new CLASS_3(VAR_7);
VAR_0 = VAR_4.FUNC_8(0);
VAR_5 = VAR_0.FUNC_9(3);
VAR_6 = VAR_5.FUNC_10((short)0);
FUNC_11("expected: IF(A3=A1,\"A1\",\"A2\") got "+VAR_6.FUNC_13(), ("IF(A3=A1,\"A1\",\"A2\")").FUNC_12(VAR_6.FUNC_13()));
//c = r.getCell((short)1);
//assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula()));
VAR_7.FUNC_7();
IMPORT_7 VAR_33 = IMPORT_17.FUNC_1("testSimpleIfFormulaWrite",".xls");
VAR_3 = new IMPORT_9(VAR_33);
VAR_4 = new CLASS_3();
VAR_0 = VAR_4.FUNC_2("testSheet1");
VAR_5 = null;
VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6=VAR_5.FUNC_4((short)0); VAR_6.FUNC_5("IF(1=1,0,1)");
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists", VAR_33.FUNC_31());
FUNC_11("length of simpleIf file is zero", (VAR_33.FUNC_26()>0));
IMPORT_7 VAR_34 = IMPORT_17.FUNC_1("testNestedIfFormula",".xls");
VAR_3 = new IMPORT_9(VAR_34);
VAR_4 = new CLASS_3();
VAR_0 = VAR_4.FUNC_2("testSheet1");
VAR_5 = null;
VAR_6 = null;
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6=VAR_5.FUNC_4((short)0);
VAR_6.FUNC_46(1);
VAR_6=VAR_5.FUNC_4((short)1);
VAR_6.FUNC_46(3);
CLASS_6 VAR_35=VAR_5.FUNC_4((short)3);
VAR_5 = VAR_0.FUNC_3((short)1);
VAR_6=VAR_5.FUNC_4((short)0);
VAR_6.FUNC_46(3);
VAR_6=VAR_5.FUNC_4((short)1);
VAR_6.FUNC_46(7);
VAR_35.FUNC_5("IF(A1=B1,AVERAGE(A1:B1),AVERAGE(A2:B2))");
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("file exists", VAR_34.FUNC_31());
FUNC_11("length of nestedIf file is zero", (VAR_34.FUNC_26()>0));
}
public void FUNC_58()
throws IMPORT_10
{
CLASS_1 VAR_29 = VAR_28.FUNC_45("HSSF.testdata.path");
CLASS_1 VAR_26 ="SUMIF(A1:A5,\">4000\",B1:B5)";
IMPORT_7 VAR_36 = new IMPORT_7(VAR_29+"/sumifformula.xls");
IMPORT_8 VAR_7 = new IMPORT_8(VAR_36);
CLASS_3 VAR_4 = new CLASS_3(VAR_7);
VAR_7.FUNC_7();
CLASS_4 VAR_0 = VAR_4.FUNC_8(0);
CLASS_5 VAR_5 = VAR_0.FUNC_9(0);
CLASS_6 VAR_6 = VAR_5.FUNC_10((short)2);
FUNC_51(VAR_26, VAR_6.FUNC_13());
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testSumIfFormula",".xls");
IMPORT_9 VAR_3 = new IMPORT_9(VAR_2);
VAR_4 = new CLASS_3();
VAR_0 = VAR_4.FUNC_2();
VAR_5 = VAR_0.FUNC_3((short)0);
VAR_6=VAR_5.FUNC_4((short)0); VAR_6.FUNC_46((double)1000);
VAR_6=VAR_5.FUNC_4((short)1); VAR_6.FUNC_46((double)1);
VAR_5 = VAR_0.FUNC_3((short)1);
VAR_6=VAR_5.FUNC_4((short)0); VAR_6.FUNC_46((double)2000);
VAR_6=VAR_5.FUNC_4((short)1); VAR_6.FUNC_46((double)2);
VAR_5 = VAR_0.FUNC_3((short)2);
VAR_6=VAR_5.FUNC_4((short)0); VAR_6.FUNC_46((double)3000);
VAR_6=VAR_5.FUNC_4((short)1); VAR_6.FUNC_46((double)3);
VAR_5 = VAR_0.FUNC_3((short)3);
VAR_6=VAR_5.FUNC_4((short)0); VAR_6.FUNC_46((double)4000);
VAR_6=VAR_5.FUNC_4((short)1); VAR_6.FUNC_46((double)4);
VAR_5 = VAR_0.FUNC_3((short)4);
VAR_6=VAR_5.FUNC_4((short)0); VAR_6.FUNC_46((double)5000);
VAR_6=VAR_5.FUNC_4((short)1); VAR_6.FUNC_46((double)5);
VAR_5 = VAR_0.FUNC_9(0);
VAR_6=VAR_5.FUNC_4((short)2); VAR_6.FUNC_5(VAR_26);
VAR_4.FUNC_6(VAR_3);
VAR_3.FUNC_7();
FUNC_11("sumif file doesnt exists", (VAR_2.FUNC_31()));
FUNC_11("sumif == 0 bytes", VAR_2.FUNC_26() > 0);
}
public void FUNC_59() throws IMPORT_10 {
IMPORT_7 VAR_37 = new IMPORT_7(VAR_28.FUNC_45("HSSF.testdata.path"));
IMPORT_7 VAR_38 = new IMPORT_7(VAR_37, "SquareMacro.xls");
IMPORT_8 VAR_7 = new IMPORT_8(VAR_38);
CLASS_3 VAR_39;
try {
VAR_39 = new CLASS_3(VAR_7);
} finally {
VAR_7.FUNC_7();
}
CLASS_4 VAR_40 = VAR_39.FUNC_8(0);
CLASS_5[] VAR_5 = {VAR_40.FUNC_9(0), VAR_40.FUNC_9(1)};
CLASS_6 VAR_41 = VAR_5[0].FUNC_10((short) 0);
FUNC_51("square(1)", VAR_41.FUNC_13());
FUNC_51(1d, VAR_41.FUNC_60(), 1e-9);
CLASS_6 VAR_42 = VAR_5[1].FUNC_10((short) 0);
FUNC_51("square(2)", VAR_42.FUNC_13());
FUNC_51(4d, VAR_42.FUNC_60(), 1e-9);
CLASS_6 VAR_43 = VAR_5[0].FUNC_10((short) 1);
FUNC_51("IF(TRUE,square(1))", VAR_43.FUNC_13());
FUNC_51(1d, VAR_43.FUNC_60(), 1e-9);
CLASS_6 VAR_44 = VAR_5[1].FUNC_10((short) 1);
FUNC_51("IF(TRUE,square(2))", VAR_44.FUNC_13());
FUNC_51(4d, VAR_44.FUNC_60(), 1e-9);
CLASS_6 VAR_45 = VAR_5[0].FUNC_10((short) 2);
FUNC_51("square(square(1))", VAR_45.FUNC_13());
FUNC_51(1d, VAR_45.FUNC_60(), 1e-9);
CLASS_6 VAR_46 = VAR_5[1].FUNC_10((short) 2);
FUNC_51("square(square(2))", VAR_46.FUNC_13());
FUNC_51(16d, VAR_46.FUNC_60(), 1e-9);
CLASS_6 VAR_47 = VAR_5[0].FUNC_10((short) 3);
FUNC_51("square(one())", VAR_47.FUNC_13());
FUNC_51(1d, VAR_47.FUNC_60(), 1e-9);
CLASS_6 VAR_48 = VAR_5[1].FUNC_10((short) 3);
FUNC_51("square(two())", VAR_48.FUNC_13());
FUNC_51(4d, VAR_48.FUNC_60(), 1e-9);
}
public void FUNC_61() throws IMPORT_10 {
IMPORT_7 VAR_37 = new IMPORT_7(VAR_28.FUNC_45("HSSF.testdata.path"));
IMPORT_7 VAR_38 = new IMPORT_7(VAR_37, "StringFormulas.xls");
IMPORT_8 VAR_7 = new IMPORT_8(VAR_38);
CLASS_3 VAR_39;
try {
VAR_39 = new CLASS_3(VAR_7);
} finally {
VAR_7.FUNC_7();
}
CLASS_6 VAR_6 = VAR_39.FUNC_8(0).FUNC_9(0).FUNC_10((short)0);
FUNC_51("String Cell value","XYZ",VAR_6.FUNC_62());
}
/** test for bug 34021*/
public void FUNC_63 () throws IMPORT_10 {
CLASS_3 VAR_49 = new CLASS_3();
CLASS_4 VAR_50 = VAR_49.FUNC_2("Sheet a.1");
CLASS_4 VAR_51 = VAR_49.FUNC_2("Sheet.A");
VAR_51.FUNC_3(1).FUNC_4((short) 2).FUNC_5("'Sheet a.1'!A1");
VAR_50.FUNC_3(1).FUNC_4((short) 2).FUNC_5("'Sheet.A'!A1");
IMPORT_7 VAR_2 = IMPORT_17.FUNC_1("testComplexSheetRefs",".xls");
VAR_49.FUNC_6(new IMPORT_9(VAR_2));
}
/*Unknown Ptg 3C*/
public void FUNC_64() throws CLASS_2 {
CLASS_1 VAR_29 = VAR_28.FUNC_45("HSSF.testdata.path");
IMPORT_7 VAR_36 = new IMPORT_7(VAR_29+"/27272_1.xls");
IMPORT_8 VAR_7 = new IMPORT_8(VAR_36);
CLASS_3 VAR_4 = new CLASS_3(VAR_7);
VAR_4.FUNC_8(0);
FUNC_51("Reference for named range ", "#REF!",VAR_4.FUNC_65(0).FUNC_66());
IMPORT_7 VAR_52 = IMPORT_7.FUNC_1("bug27272_1",".xls");
VAR_4.FUNC_6(new IMPORT_9(VAR_52));
VAR_28.VAR_3.FUNC_67("Open "+VAR_52.FUNC_68()+" in Excel");
}
/*Unknown Ptg 3D*/
public void FUNC_69() throws CLASS_2 {
CLASS_1 VAR_29 = VAR_28.FUNC_45("HSSF.testdata.path");
IMPORT_7 VAR_36 = new IMPORT_7(VAR_29+"/27272_2.xls");
IMPORT_8 VAR_7 = new IMPORT_8(VAR_36);
CLASS_3 VAR_4 = new CLASS_3(VAR_7);
FUNC_51("Reference for named range ", "#REF!",VAR_4.FUNC_65(0).FUNC_66());
IMPORT_7 VAR_52 = IMPORT_7.FUNC_1("bug27272_2",".xls");
VAR_4.FUNC_6(new IMPORT_9(VAR_52));
VAR_28.VAR_3.FUNC_67("Open "+VAR_52.FUNC_68()+" in Excel");
}
/* MissingArgPtg */
public void FUNC_70() throws CLASS_2 {
CLASS_3 VAR_4 = new CLASS_3();
CLASS_6 VAR_53 = VAR_4.FUNC_2("Sheet1").FUNC_3(4).FUNC_4((short) 0);
VAR_53.FUNC_5("IF(A1=\"A\",1,)");
}
public static void FUNC_71(CLASS_1 [] VAR_54) {
VAR_28.VAR_3
.FUNC_67("Testing org.apache.poi.hssf.usermodel.TestFormulas");
IMPORT_13.VAR_55.VAR_56.FUNC_72(CLASS_0.class);
}
}
| 0.994558 | {'IMPORT_0': 'org', 'IMPORT_1': 'apache', 'IMPORT_2': 'poi', 'IMPORT_3': 'hssf', 'IMPORT_4': 'usermodel', 'IMPORT_5': 'java', 'IMPORT_6': 'io', 'IMPORT_7': 'File', 'IMPORT_8': 'FileInputStream', 'IMPORT_9': 'FileOutputStream', 'IMPORT_10': 'IOException', 'IMPORT_11': 'util', 'IMPORT_12': 'Date', 'IMPORT_13': 'junit', 'IMPORT_14': 'framework', 'IMPORT_15': 'TestCase', 'IMPORT_16': 'CellReference', 'IMPORT_17': 'TempFile', 'CLASS_0': 'TestFormulas', 'CLASS_1': 'String', 'VAR_0': 's', 'FUNC_0': 'testBasicAddIntegers', 'CLASS_2': 'Exception', 'VAR_1': 'rownum', 'VAR_2': 'file', 'FUNC_1': 'createTempFile', 'VAR_3': 'out', 'CLASS_3': 'HSSFWorkbook', 'VAR_4': 'wb', 'CLASS_4': 'HSSFSheet', 'FUNC_2': 'createSheet', 'CLASS_5': 'HSSFRow', 'VAR_5': 'r', 'CLASS_6': 'HSSFCell', 'VAR_6': 'c', 'FUNC_3': 'createRow', 'FUNC_4': 'createCell', 'FUNC_5': 'setCellFormula', 'FUNC_6': 'write', 'FUNC_7': 'close', 'VAR_7': 'in', 'FUNC_8': 'getSheetAt', 'FUNC_9': 'getRow', 'FUNC_10': 'getCell', 'FUNC_11': 'assertTrue', 'FUNC_12': 'equals', 'FUNC_13': 'getCellFormula', 'FUNC_14': 'testAddIntegers', 'FUNC_15': 'binomialOperator', 'FUNC_16': 'testMultplyIntegers', 'FUNC_17': 'testSubtractIntegers', 'FUNC_18': 'testDivideIntegers', 'FUNC_19': 'testPowerIntegers', 'FUNC_20': 'testConcatIntegers', 'FUNC_21': 'testOrderOfOperationsMultiply', 'FUNC_22': 'orderTest', 'FUNC_23': 'testOrderOfOperationsPower', 'FUNC_24': 'testParenthesis', 'FUNC_25': 'testReferencesOpr', 'VAR_8': 'operation', 'VAR_9': 'k', 'VAR_10': 'length', 'FUNC_26': 'length', 'FUNC_27': 'operationRefTest', 'FUNC_28': 'testFloat', 'FUNC_29': 'floatTest', 'VAR_11': 'operator', 'VAR_12': 'Float', 'VAR_13': 'MIN_VALUE', 'VAR_14': 'x', 'VAR_15': 'Short', 'VAR_16': 'MAX_VALUE', 'VAR_17': 'y', 'FUNC_30': 'getLastRowNum', 'FUNC_31': 'exists', 'FUNC_32': 'floatVerify', 'FUNC_33': 'testAreaSum', 'FUNC_34': 'areaFunctionTest', 'FUNC_35': 'testAreaAverage', 'FUNC_36': 'testRefArraySum', 'FUNC_37': 'refArrayFunctionTest', 'FUNC_38': 'testAreaArraySum', 'FUNC_39': 'refAreaArrayFunctionTest', 'VAR_18': 'ref', 'VAR_19': 'ref2', 'VAR_20': 'refx1', 'VAR_21': 'refy1', 'VAR_22': 'refx2', 'VAR_23': 'refy2', 'VAR_24': 'cr', 'FUNC_40': 'toString', 'FUNC_41': 'operationalRefVerify', 'VAR_25': 'formula', 'FUNC_42': 'binomialVerify', 'VAR_26': 'function', 'FUNC_43': 'testAbsRefs', 'FUNC_44': 'testSheetFunctions', 'VAR_27': 'filename', 'VAR_28': 'System', 'FUNC_45': 'getProperty', 'FUNC_46': 'setCellValue', 'FUNC_47': 'getSheet', 'FUNC_48': 'testRVAoperands', 'FUNC_49': 'testStringFormulas', 'VAR_29': 'readFilename', 'VAR_30': 'separator', 'FUNC_50': 'testLogicalFormulas', 'FUNC_51': 'assertEquals', 'FUNC_52': 'testDateFormulas', 'CLASS_7': 'HSSFCellStyle', 'VAR_31': 'cellStyle', 'FUNC_53': 'createCellStyle', 'FUNC_54': 'setDataFormat', 'VAR_32': 'HSSFDataFormat', 'FUNC_55': 'getBuiltinFormat', 'FUNC_56': 'setCellStyle', 'FUNC_57': 'testIfFormulas', 'VAR_33': 'simpleIf', 'VAR_34': 'nestedIf', 'VAR_35': 'formulaCell', 'FUNC_58': 'testSumIf', 'VAR_36': 'inFile', 'FUNC_59': 'testSquareMacro', 'VAR_37': 'dir', 'VAR_38': 'xls', 'VAR_39': 'w', 'VAR_40': 's0', 'VAR_41': 'a1', 'FUNC_60': 'getNumericCellValue', 'VAR_42': 'a2', 'VAR_43': 'b1', 'VAR_44': 'b2', 'VAR_45': 'c1', 'VAR_46': 'c2', 'VAR_47': 'd1', 'VAR_48': 'd2', 'FUNC_61': 'testStringFormulaRead', 'FUNC_62': 'getStringCellValue', 'FUNC_63': 'testComplexSheetRefs', 'VAR_49': 'sb', 'VAR_50': 's1', 'VAR_51': 's2', 'FUNC_64': 'test27272_1', 'FUNC_65': 'getNameAt', 'FUNC_66': 'getReference', 'VAR_52': 'outF', 'FUNC_67': 'println', 'FUNC_68': 'getAbsolutePath', 'FUNC_69': 'test27272_2', 'FUNC_70': 'testMissingArgPtg', 'VAR_53': 'cell', 'FUNC_71': 'main', 'VAR_54': 'args', 'VAR_55': 'textui', 'VAR_56': 'TestRunner', 'FUNC_72': 'run'} | java | error | 0 |
/*
* #%L
* =====================================================
* _____ _ ____ _ _ _ _
* |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | |
* | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| |
* | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ |
* |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_|
* \____/
*
* =====================================================
*
* Hochschule Hannover
* (University of Applied Sciences and Arts, Hannover)
* Faculty IV, Dept. of Computer Science
* Ricklinger Stadtweg 118, 30459 Hannover, Germany
*
* Email: <EMAIL>
* Website: http://trust.f4.hs-hannover.de
*
* This file is part of irongenlog, version 0.1.0, implemented by the Trust@HsH
* research group at the Hochschule Hannover.
* %%
* Copyright (C) 2014 - 2016 Trust@HsH
* %%
* 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.
* #L%
*/
package de.hshannover.f4.trust.irongenlog.publisher.strategies;
import java.util.logging.Logger;
import org.codehaus.jackson.JsonNode;
import org.w3c.dom.Document;
import de.hshannover.f4.trust.ifmapj.binding.IfmapStrings;
import de.hshannover.f4.trust.ifmapj.channel.SSRC;
import de.hshannover.f4.trust.ifmapj.exception.IfmapErrorResult;
import de.hshannover.f4.trust.ifmapj.exception.IfmapException;
import de.hshannover.f4.trust.ifmapj.identifier.AccessRequest;
import de.hshannover.f4.trust.ifmapj.identifier.Device;
import de.hshannover.f4.trust.ifmapj.identifier.Identifiers;
import de.hshannover.f4.trust.ifmapj.identifier.IpAddress;
import de.hshannover.f4.trust.ifmapj.identifier.MacAddress;
import de.hshannover.f4.trust.ifmapj.messages.MetadataLifetime;
import de.hshannover.f4.trust.ifmapj.messages.PublishDelete;
import de.hshannover.f4.trust.ifmapj.messages.PublishUpdate;
import de.hshannover.f4.trust.ifmapj.messages.Requests;
import de.hshannover.f4.trust.irongenlog.publisher.PublishLogDataStrategy;
/**
* This class implements the publish strategy for dhcp events comming from
* dnsmasq
*
* @author <NAME>
*
*/
public class PublishDnsMasqDhcpEvents extends PublishLogDataStrategy {
private static final Logger LOGGER = Logger.getLogger(PublishDnsMasqDhcpEvents.class.getName());
/**
* Method checks for right publish strategy
*
* @param ssrc
* : the ssrc to publish data
* @param rootNode
* : the json message root node
*/
@Override
public void publishLogData(SSRC ssrc, JsonNode rootNode) {
if (rootNode.path("strategy").getTextValue().equals("dnsmasq-dhcp")) {
String method = rootNode.path("METHOD").getTextValue();
if (method.equals("DHCPDISCOVER")) {
publishDhcpDiscover(ssrc, rootNode);
} else if (method.equals("DHCPOFFER")) {
// nothing to do right now
} else if (method.equals("DHCPREQUEST")) {
publishDhcpRequest(ssrc, rootNode);
} else if (method.equals("DHCPACK")) {
publishDhcpAck(ssrc, rootNode);
}
}
}
/**
* Method to publish the dhcp logdata performed by DHCP Discover message
*
* @param ssrc
* : the ssrc to publish data
* @param rootNode
* : the json message root node
*/
private void publishDhcpDiscover(SSRC ssrc, JsonNode rootNode) {
try {
MacAddress macHost = Identifiers.createMac(rootNode.path("MAC").getTextValue());
Device dhcpserver = Identifiers.createDev(rootNode.path("DHCPSERVERNAME").getTextValue());
Document docDiscoMac = getMetadataFactory().createDiscoveredBy();
PublishUpdate publishDiscoMac = Requests.createPublishUpdate(macHost, dhcpserver, docDiscoMac,
MetadataLifetime.session);
ssrc.publish(Requests.createPublishReq(publishDiscoMac));
} catch (IfmapErrorResult e) {
LOGGER.severe("Error publishing dhcp data: " + e);
} catch (IfmapException e) {
LOGGER.severe("Error publishing dhcp data: " + e);
}
}
/**
* Method to publish the dhcp logdata performed by DHCP Request message
*
* @param ssrc
* : the ssrc to publish data
* @param rootNode
* : the json message root node
*/
private void publishDhcpRequest(SSRC ssrc, JsonNode rootNode) {
try {
// accessrequest to mac
MacAddress macHost = Identifiers.createMac(rootNode.path("MAC").getTextValue());
AccessRequest ar = Identifiers.createAr("DHCPREQUEST_" + rootNode.path("IP").getTextValue());
Document docArMac = getMetadataFactory().createArMac();
PublishUpdate publishArMac = Requests.createPublishUpdate(macHost, ar, docArMac, MetadataLifetime.session);
ssrc.publish(Requests.createPublishReq(publishArMac));
// del ip-mac
IpAddress ipHost = Identifiers.createIp4(rootNode.path("IP").getTextValue());
PublishDelete del = Requests.createPublishDelete(ipHost, macHost,
"meta:ip-mac[@ifmap-publisher-id='" + ssrc.getPublisherId() + "']");
del.addNamespaceDeclaration(IfmapStrings.STD_METADATA_PREFIX, IfmapStrings.STD_METADATA_NS_URI);
ssrc.publish(Requests.createPublishReq(del));
// ip to mac
Document docIpMac = getMetadataFactory().createIpMac(null, null,
rootNode.path("DHCPSERVERNAME").getTextValue());
PublishUpdate publishIpMac = Requests.createPublishUpdate(macHost, ipHost, docIpMac,
MetadataLifetime.session);
ssrc.publish(Requests.createPublishReq(publishIpMac));
// accessrequest to ip
Document docIpAr = getMetadataFactory().createArIp();
PublishUpdate publishIpAr = Requests.createPublishUpdate(ar, ipHost, docIpAr, MetadataLifetime.session);
ssrc.publish(Requests.createPublishReq(publishIpAr));
} catch (IfmapErrorResult e) {
LOGGER.severe("Error publishing dhcp data: " + e);
} catch (IfmapException e) {
LOGGER.severe("Error publishing dhcp data: " + e);
}
}
/**
* Method to publish the dhcp logdata performed by DHCP Request message
*
* @param ssrc
* : the ssrc to publish data
* @param rootNode
* : the json message root node
*/
private void publishDhcpAck(SSRC ssrc, JsonNode rootNode) {
try {
AccessRequest ar = Identifiers.createAr("DHCPREQUEST_" + rootNode.path("IP").getTextValue());
Device dhcpserver = Identifiers.createDev(rootNode.path("DHCPSERVERNAME").getTextValue());
Document docAuthAr = getMetadataFactory().createAuthBy();
PublishUpdate publishDiscoMac = Requests.createPublishUpdate(ar, dhcpserver, docAuthAr,
MetadataLifetime.session);
ssrc.publish(Requests.createPublishReq(publishDiscoMac));
} catch (IfmapErrorResult e) {
LOGGER.severe("Error publishing dhcp data: " + e);
} catch (IfmapException e) {
LOGGER.severe("Error publishing dhcp data: " + e);
}
}
}
| /*
* #%L
* =====================================================
* _____ _ ____ _ _ _ _
* |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | |
* | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| |
* | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ |
* |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_|
* \____/
*
* =====================================================
*
* Hochschule Hannover
* (University of Applied Sciences and Arts, Hannover)
* Faculty IV, Dept. of Computer Science
* Ricklinger Stadtweg 118, 30459 Hannover, Germany
*
* Email: <EMAIL>
* Website: http://trust.f4.hs-hannover.de
*
* This file is part of irongenlog, version 0.1.0, implemented by the Trust@HsH
* research group at the Hochschule Hannover.
* %%
* Copyright (C) 2014 - 2016 Trust@HsH
* %%
* 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.
* #L%
*/
package de.hshannover.f4.IMPORT_0.IMPORT_1.publisher.IMPORT_2;
import IMPORT_3.IMPORT_4.IMPORT_5.IMPORT_6;
import IMPORT_7.IMPORT_8.jackson.IMPORT_9;
import IMPORT_7.IMPORT_10.IMPORT_11.IMPORT_12;
import de.hshannover.f4.IMPORT_0.ifmapj.binding.IMPORT_13;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_14.SSRC;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_15.IMPORT_16;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_15.IMPORT_17;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_18.IMPORT_19;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_18.IMPORT_20;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_18.Identifiers;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_18.IMPORT_21;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_18.MacAddress;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_22.IMPORT_23;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_22.PublishDelete;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_22.IMPORT_24;
import de.hshannover.f4.IMPORT_0.ifmapj.IMPORT_22.Requests;
import de.hshannover.f4.IMPORT_0.IMPORT_1.publisher.IMPORT_25;
/**
* This class implements the publish strategy for dhcp events comming from
* dnsmasq
*
* @author <NAME>
*
*/
public class PublishDnsMasqDhcpEvents extends IMPORT_25 {
private static final IMPORT_6 VAR_0 = IMPORT_6.FUNC_0(PublishDnsMasqDhcpEvents.class.FUNC_1());
/**
* Method checks for right publish strategy
*
* @param ssrc
* : the ssrc to publish data
* @param rootNode
* : the json message root node
*/
@Override
public void FUNC_2(SSRC ssrc, IMPORT_9 rootNode) {
if (rootNode.FUNC_3("strategy").getTextValue().FUNC_4("dnsmasq-dhcp")) {
CLASS_0 method = rootNode.FUNC_3("METHOD").getTextValue();
if (method.FUNC_4("DHCPDISCOVER")) {
FUNC_5(ssrc, rootNode);
} else if (method.FUNC_4("DHCPOFFER")) {
// nothing to do right now
} else if (method.FUNC_4("DHCPREQUEST")) {
FUNC_6(ssrc, rootNode);
} else if (method.FUNC_4("DHCPACK")) {
publishDhcpAck(ssrc, rootNode);
}
}
}
/**
* Method to publish the dhcp logdata performed by DHCP Discover message
*
* @param ssrc
* : the ssrc to publish data
* @param rootNode
* : the json message root node
*/
private void FUNC_5(SSRC ssrc, IMPORT_9 rootNode) {
try {
MacAddress macHost = Identifiers.createMac(rootNode.FUNC_3("MAC").getTextValue());
IMPORT_20 VAR_1 = Identifiers.FUNC_7(rootNode.FUNC_3("DHCPSERVERNAME").getTextValue());
IMPORT_12 docDiscoMac = FUNC_8().FUNC_9();
IMPORT_24 VAR_2 = Requests.FUNC_10(macHost, VAR_1, docDiscoMac,
IMPORT_23.VAR_3);
ssrc.publish(Requests.FUNC_11(VAR_2));
} catch (IMPORT_16 VAR_4) {
VAR_0.FUNC_12("Error publishing dhcp data: " + VAR_4);
} catch (IMPORT_17 VAR_4) {
VAR_0.FUNC_12("Error publishing dhcp data: " + VAR_4);
}
}
/**
* Method to publish the dhcp logdata performed by DHCP Request message
*
* @param ssrc
* : the ssrc to publish data
* @param rootNode
* : the json message root node
*/
private void FUNC_6(SSRC ssrc, IMPORT_9 rootNode) {
try {
// accessrequest to mac
MacAddress macHost = Identifiers.createMac(rootNode.FUNC_3("MAC").getTextValue());
IMPORT_19 VAR_5 = Identifiers.FUNC_13("DHCPREQUEST_" + rootNode.FUNC_3("IP").getTextValue());
IMPORT_12 VAR_6 = FUNC_8().FUNC_14();
IMPORT_24 publishArMac = Requests.FUNC_10(macHost, VAR_5, VAR_6, IMPORT_23.VAR_3);
ssrc.publish(Requests.FUNC_11(publishArMac));
// del ip-mac
IMPORT_21 ipHost = Identifiers.FUNC_15(rootNode.FUNC_3("IP").getTextValue());
PublishDelete del = Requests.FUNC_16(ipHost, macHost,
"meta:ip-mac[@ifmap-publisher-id='" + ssrc.FUNC_17() + "']");
del.FUNC_18(IMPORT_13.VAR_7, IMPORT_13.STD_METADATA_NS_URI);
ssrc.publish(Requests.FUNC_11(del));
// ip to mac
IMPORT_12 VAR_8 = FUNC_8().createIpMac(null, null,
rootNode.FUNC_3("DHCPSERVERNAME").getTextValue());
IMPORT_24 publishIpMac = Requests.FUNC_10(macHost, ipHost, VAR_8,
IMPORT_23.VAR_3);
ssrc.publish(Requests.FUNC_11(publishIpMac));
// accessrequest to ip
IMPORT_12 docIpAr = FUNC_8().FUNC_19();
IMPORT_24 VAR_9 = Requests.FUNC_10(VAR_5, ipHost, docIpAr, IMPORT_23.VAR_3);
ssrc.publish(Requests.FUNC_11(VAR_9));
} catch (IMPORT_16 VAR_4) {
VAR_0.FUNC_12("Error publishing dhcp data: " + VAR_4);
} catch (IMPORT_17 VAR_4) {
VAR_0.FUNC_12("Error publishing dhcp data: " + VAR_4);
}
}
/**
* Method to publish the dhcp logdata performed by DHCP Request message
*
* @param ssrc
* : the ssrc to publish data
* @param rootNode
* : the json message root node
*/
private void publishDhcpAck(SSRC ssrc, IMPORT_9 rootNode) {
try {
IMPORT_19 VAR_5 = Identifiers.FUNC_13("DHCPREQUEST_" + rootNode.FUNC_3("IP").getTextValue());
IMPORT_20 VAR_1 = Identifiers.FUNC_7(rootNode.FUNC_3("DHCPSERVERNAME").getTextValue());
IMPORT_12 VAR_10 = FUNC_8().FUNC_20();
IMPORT_24 VAR_2 = Requests.FUNC_10(VAR_5, VAR_1, VAR_10,
IMPORT_23.VAR_3);
ssrc.publish(Requests.FUNC_11(VAR_2));
} catch (IMPORT_16 VAR_4) {
VAR_0.FUNC_12("Error publishing dhcp data: " + VAR_4);
} catch (IMPORT_17 VAR_4) {
VAR_0.FUNC_12("Error publishing dhcp data: " + VAR_4);
}
}
}
| 0.605563 | {'IMPORT_0': 'trust', 'IMPORT_1': 'irongenlog', 'IMPORT_2': 'strategies', 'IMPORT_3': 'java', 'IMPORT_4': 'util', 'IMPORT_5': 'logging', 'IMPORT_6': 'Logger', 'IMPORT_7': 'org', 'IMPORT_8': 'codehaus', 'IMPORT_9': 'JsonNode', 'IMPORT_10': 'w3c', 'IMPORT_11': 'dom', 'IMPORT_12': 'Document', 'IMPORT_13': 'IfmapStrings', 'IMPORT_14': 'channel', 'IMPORT_15': 'exception', 'IMPORT_16': 'IfmapErrorResult', 'IMPORT_17': 'IfmapException', 'IMPORT_18': 'identifier', 'IMPORT_19': 'AccessRequest', 'IMPORT_20': 'Device', 'IMPORT_21': 'IpAddress', 'IMPORT_22': 'messages', 'IMPORT_23': 'MetadataLifetime', 'IMPORT_24': 'PublishUpdate', 'IMPORT_25': 'PublishLogDataStrategy', 'VAR_0': 'LOGGER', 'FUNC_0': 'getLogger', 'FUNC_1': 'getName', 'FUNC_2': 'publishLogData', 'FUNC_3': 'path', 'FUNC_4': 'equals', 'CLASS_0': 'String', 'FUNC_5': 'publishDhcpDiscover', 'FUNC_6': 'publishDhcpRequest', 'VAR_1': 'dhcpserver', 'FUNC_7': 'createDev', 'FUNC_8': 'getMetadataFactory', 'FUNC_9': 'createDiscoveredBy', 'VAR_2': 'publishDiscoMac', 'FUNC_10': 'createPublishUpdate', 'VAR_3': 'session', 'FUNC_11': 'createPublishReq', 'VAR_4': 'e', 'FUNC_12': 'severe', 'VAR_5': 'ar', 'FUNC_13': 'createAr', 'VAR_6': 'docArMac', 'FUNC_14': 'createArMac', 'FUNC_15': 'createIp4', 'FUNC_16': 'createPublishDelete', 'FUNC_17': 'getPublisherId', 'FUNC_18': 'addNamespaceDeclaration', 'VAR_7': 'STD_METADATA_PREFIX', 'VAR_8': 'docIpMac', 'FUNC_19': 'createArIp', 'VAR_9': 'publishIpAr', 'VAR_10': 'docAuthAr', 'FUNC_20': 'createAuthBy'} | java | error | 0 |
package com.bol.model;
public enum GameStatus {
CONTINUE,
CHANGE_TURN,
ILLEGAL_PLAYER,
GAME_OVER
}
| package IMPORT_0.IMPORT_1.IMPORT_2;
public enum CLASS_0 {
VAR_0,
VAR_1,
VAR_2,
VAR_3
}
| 0.99806 | {'IMPORT_0': 'com', 'IMPORT_1': 'bol', 'IMPORT_2': 'model', 'CLASS_0': 'GameStatus', 'VAR_0': 'CONTINUE', 'VAR_1': 'CHANGE_TURN', 'VAR_2': 'ILLEGAL_PLAYER', 'VAR_3': 'GAME_OVER'} | java | Texto | 61.54% |
/**
* Provides classes implementing subscription related functionality.
*/
package com.cinnober.ciguan.subscription.impl; | /**
* Provides classes implementing subscription related functionality.
*/
package IMPORT_0.IMPORT_1.ciguan.IMPORT_2.IMPORT_3; | 0.853112 | {'IMPORT_0': 'com', 'IMPORT_1': 'cinnober', 'IMPORT_2': 'subscription', 'IMPORT_3': 'impl'} | java | Texto | 100.00% |
package com.github.crimsondawn45.basicshields.mixin;
import org.spongepowered.asm.mixin.Mixin;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ShieldItem;
/**
* Replace the vanilla iron shield's translation key
*/
@Mixin(ShieldItem.class)
public class ShieldItemMixin extends Item {
private static final String TRANSLATION_KEY = "item.basicshields.iron_shield";
public ShieldItemMixin(Settings settings) {
super(settings);
}
@Override
public String getTranslationKey(ItemStack stack) {
if (BlockItem.getBlockEntityNbt(stack) != null) {
return TRANSLATION_KEY + "." + ShieldItem.getColor(stack).getName();
}
return TRANSLATION_KEY;
}
}
| package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.mixin;
import IMPORT_4.IMPORT_5.IMPORT_6.mixin.IMPORT_7;
import IMPORT_8.minecraft.IMPORT_9.IMPORT_10;
import IMPORT_8.minecraft.IMPORT_9.Item;
import IMPORT_8.minecraft.IMPORT_9.IMPORT_11;
import IMPORT_8.minecraft.IMPORT_9.ShieldItem;
/**
* Replace the vanilla iron shield's translation key
*/
@IMPORT_7(ShieldItem.class)
public class CLASS_0 extends Item {
private static final CLASS_1 VAR_0 = "item.basicshields.iron_shield";
public CLASS_0(Settings VAR_1) {
super(VAR_1);
}
@Override
public CLASS_1 FUNC_0(IMPORT_11 VAR_2) {
if (IMPORT_10.FUNC_1(VAR_2) != null) {
return VAR_0 + "." + ShieldItem.FUNC_2(VAR_2).FUNC_3();
}
return VAR_0;
}
}
| 0.925451 | {'IMPORT_0': 'com', 'IMPORT_1': 'github', 'IMPORT_2': 'crimsondawn45', 'IMPORT_3': 'basicshields', 'IMPORT_4': 'org', 'IMPORT_5': 'spongepowered', 'IMPORT_6': 'asm', 'IMPORT_7': 'Mixin', 'IMPORT_8': 'net', 'IMPORT_9': 'item', 'IMPORT_10': 'BlockItem', 'IMPORT_11': 'ItemStack', 'CLASS_0': 'ShieldItemMixin', 'CLASS_1': 'String', 'VAR_0': 'TRANSLATION_KEY', 'VAR_1': 'settings', 'FUNC_0': 'getTranslationKey', 'VAR_2': 'stack', 'FUNC_1': 'getBlockEntityNbt', 'FUNC_2': 'getColor', 'FUNC_3': 'getName'} | java | Procedural | 43.14% |
import java.util.Arrays;
import java.util.Set ;
import java.util.HashSet;
public class Solution {
public static boolean checkIfExist(int[] arr) {
// In the problem ” Check If N and Its Double Exist” we are given an array of n elements. Array length is greater than or equal to two.
// Our task is to check if there exists a pair in the array such that the first value is double the second value
// More formally we need to check if there exists i,j for which i <n,j<n and arr[i]=2*arr[j].
Set<Integer> seen = new HashSet<>(); // We can solve this problem in a better time complexity using an unordered map or unordered set
for (int i : arr) { // 1.Traverse the array.
if (seen.contains(2 * i) || (i % 2 == 0 && seen.contains(i / 2))) // 2.For every element in the array check if it’s double or its half already exists it the map.
return true;
seen.add(i);
}
return false;
} // 3.If the condition is true simply return true else add that element into the map.
public static void main(String[] args) {
int [] arr = {7,1,14,11};
boolean ans=checkIfExist(arr);
System.out.println(ans);
}
}
| import java.IMPORT_0.IMPORT_1;
import java.IMPORT_0.IMPORT_2 ;
import java.IMPORT_0.IMPORT_3;
public class CLASS_0 {
public static boolean checkIfExist(int[] VAR_0) {
// In the problem ” Check If N and Its Double Exist” we are given an array of n elements. Array length is greater than or equal to two.
// Our task is to check if there exists a pair in the array such that the first value is double the second value
// More formally we need to check if there exists i,j for which i <n,j<n and arr[i]=2*arr[j].
IMPORT_2<CLASS_1> VAR_1 = new IMPORT_3<>(); // We can solve this problem in a better time complexity using an unordered map or unordered set
for (int VAR_2 : VAR_0) { // 1.Traverse the array.
if (VAR_1.FUNC_0(2 * VAR_2) || (VAR_2 % 2 == 0 && VAR_1.FUNC_0(VAR_2 / 2))) // 2.For every element in the array check if it’s double or its half already exists it the map.
return true;
VAR_1.FUNC_1(VAR_2);
}
return false;
} // 3.If the condition is true simply return true else add that element into the map.
public static void FUNC_2(CLASS_2[] VAR_3) {
int [] VAR_0 = {7,1,14,11};
boolean VAR_4=checkIfExist(VAR_0);
VAR_5.VAR_6.FUNC_3(VAR_4);
}
}
| 0.736167 | {'IMPORT_0': 'util', 'IMPORT_1': 'Arrays', 'IMPORT_2': 'Set', 'IMPORT_3': 'HashSet', 'CLASS_0': 'Solution', 'VAR_0': 'arr', 'CLASS_1': 'Integer', 'VAR_1': 'seen', 'VAR_2': 'i', 'FUNC_0': 'contains', 'FUNC_1': 'add', 'FUNC_2': 'main', 'CLASS_2': 'String', 'VAR_3': 'args', 'VAR_4': 'ans', 'VAR_5': 'System', 'VAR_6': 'out', 'FUNC_3': 'println'} | java | OOP | 62.10% |
/**
* The pointTurn method turns the robot to a target heading, automatically picking the turn
* direction that is the shortest distance to turn to arrive at the target.
*
* @param targetHeading The direction in which the robot will move.
* @param time The maximum time the move can take before the code moves on.
* @param power The power at which the robot will move.
* @return A boolean that tells use whether or not the robot is moving.
*/
@Override
public boolean pointTurn(double power, double targetHeading, double time)
{
power = Math.abs(power);
double currentHeading = getHeadingDbl();
if (Math.abs(targetHeading) > 170 && currentHeading < 0.0)
{
currentHeading += 360;
}
if (!moving)
{
initialHeading = getHeadingDbl();
error = initialHeading - targetHeading;
if (error > 180)
{
error -= 360;
}
else if (error < -180)
{
error += 360;
}
if (error < 0)
{
directionalPower = power;
}
else
{
directionalPower = -power;
}
if ( Math.abs(error) < 60 )
{
directionalPower = -error * 0.01;
if (directionalPower > 0 )
{
directionalPower = Range.clip( directionalPower, 0.15, power);
}
else
{
directionalPower = Range.clip(directionalPower, -power, -0.15);
}
}
setMode(DcMotor.RunMode.RUN_USING_ENCODER);
resetStartTime();
moving = true;
}
joystickDrive(0.0, 0.0, directionalPower, 0.0, power);
if(Math.abs(currentHeading - targetHeading) < 4.0 || getRuntime() > time)
{
stopMotors();
moving = false;
}
return !moving;
} | /**
* The pointTurn method turns the robot to a target heading, automatically picking the turn
* direction that is the shortest distance to turn to arrive at the target.
*
* @param targetHeading The direction in which the robot will move.
* @param time The maximum time the move can take before the code moves on.
* @param power The power at which the robot will move.
* @return A boolean that tells use whether or not the robot is moving.
*/
@VAR_0
public boolean pointTurn(double power, double VAR_1, double VAR_2)
{
power = VAR_3.abs(power);
double currentHeading = getHeadingDbl();
if (VAR_3.abs(VAR_1) > 170 && currentHeading < 0.0)
{
currentHeading += 360;
}
if (!VAR_4)
{
initialHeading = getHeadingDbl();
error = initialHeading - VAR_1;
if (error > 180)
{
error -= 360;
}
else if (error < -180)
{
error += 360;
}
if (error < 0)
{
directionalPower = power;
}
else
{
directionalPower = -power;
}
if ( VAR_3.abs(error) < 60 )
{
directionalPower = -error * 0.01;
if (directionalPower > 0 )
{
directionalPower = VAR_5.FUNC_0( directionalPower, 0.15, power);
}
else
{
directionalPower = VAR_5.FUNC_0(directionalPower, -power, -0.15);
}
}
setMode(VAR_6.RunMode.RUN_USING_ENCODER);
FUNC_1();
VAR_4 = true;
}
joystickDrive(0.0, 0.0, directionalPower, 0.0, power);
if(VAR_3.abs(currentHeading - VAR_1) < 4.0 || FUNC_2() > VAR_2)
{
FUNC_3();
VAR_4 = false;
}
return !VAR_4;
} | 0.579563 | {'VAR_0': 'Override', 'VAR_1': 'targetHeading', 'VAR_2': 'time', 'VAR_3': 'Math', 'VAR_4': 'moving', 'VAR_5': 'Range', 'FUNC_0': 'clip', 'VAR_6': 'DcMotor', 'FUNC_1': 'resetStartTime', 'FUNC_2': 'getRuntime', 'FUNC_3': 'stopMotors'} | java | Procedural | 45.78% |
/*
* Copyright (c) 2016 by <NAME>
*
* 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 eu.hansolo.medusa.skins;
import eu.hansolo.medusa.Fonts;
import eu.hansolo.medusa.Gauge;
import eu.hansolo.medusa.Section;
import eu.hansolo.medusa.TickLabelOrientation;
import eu.hansolo.medusa.tools.Helper;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import javafx.beans.InvalidationListener;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.CacheHint;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderStroke;
import javafx.scene.layout.BorderStrokeStyle;
import javafx.scene.layout.BorderWidths;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import static eu.hansolo.medusa.tools.Helper.formatNumber;
/**
* Created by hansolo on 08.02.16.
*/
public class DigitalSkin extends GaugeSkinBase {
private static final double START_ANGLE = -30;
private static final double ANGLE_RANGE = 300;
private double size;
private double center;
private Pane pane;
private Canvas backgroundCanvas;
private GraphicsContext backgroundCtx;
private Canvas barCanvas;
private GraphicsContext barCtx;
private Text valueBkgText;
private Text valueText;
private Color barColor;
private Color valueColor;
private Color titleColor;
private Color subTitleColor;
private Color unitColor;
private double minValue;
private double maxValue;
private double range;
private double angleStep;
private boolean isStartFromZero;
private double barWidth;
private Locale locale;
private boolean sectionsVisible;
private List<Section> sections;
private boolean thresholdVisible;
private Color thresholdColor;
private InvalidationListener currentValueListener;
// ******************** Constructors **************************************
public DigitalSkin(Gauge gauge) {
super(gauge);
if (gauge.isAutoScale()) gauge.calcAutoScale();
minValue = gauge.getMinValue();
maxValue = gauge.getMaxValue();
range = gauge.getRange();
angleStep = ANGLE_RANGE / range;
locale = gauge.getLocale();
barColor = gauge.getBarColor();
valueColor = gauge.getValueColor();
titleColor = gauge.getTitleColor();
subTitleColor = gauge.getSubTitleColor();
unitColor = gauge.getUnitColor();
isStartFromZero = gauge.isStartFromZero();
sectionsVisible = gauge.getSectionsVisible();
sections = gauge.getSections();
thresholdVisible = gauge.isThresholdVisible();
thresholdColor = gauge.getThresholdColor();
currentValueListener = o -> setBar(gauge.getCurrentValue());
initGraphics();
registerListeners();
setBar(gauge.getCurrentValue());
}
// ******************** Initialization ************************************
private void initGraphics() {
// Set initial size
if (Double.compare(gauge.getPrefWidth(), 0.0) <= 0 || Double.compare(gauge.getPrefHeight(), 0.0) <= 0 ||
Double.compare(gauge.getWidth(), 0.0) <= 0 || Double.compare(gauge.getHeight(), 0.0) <= 0) {
if (gauge.getPrefWidth() > 0 && gauge.getPrefHeight() > 0) {
gauge.setPrefSize(gauge.getPrefWidth(), gauge.getPrefHeight());
} else {
gauge.setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT);
}
}
backgroundCanvas = new Canvas(PREFERRED_WIDTH, PREFERRED_HEIGHT);
backgroundCtx = backgroundCanvas.getGraphicsContext2D();
barCanvas = new Canvas(PREFERRED_WIDTH, PREFERRED_HEIGHT);
barCtx = barCanvas.getGraphicsContext2D();
valueBkgText = new Text();
valueBkgText.setStroke(null);
valueBkgText.setFill(Helper.getTranslucentColorFrom(valueColor, 0.1));
valueText = new Text();
valueText.setStroke(null);
valueText.setFill(valueColor);
Helper.enableNode(valueText, gauge.isValueVisible());
pane = new Pane(backgroundCanvas, barCanvas, valueBkgText, valueText);
pane.setBackground(new Background(new BackgroundFill(gauge.getBackgroundPaint(), new CornerRadii(1024), Insets.EMPTY)));
pane.setBorder(new Border(new BorderStroke(gauge.getBorderPaint(), BorderStrokeStyle.SOLID, new CornerRadii(1024), new BorderWidths(gauge.getBorderWidth()))));
getChildren().setAll(pane);
}
@Override protected void registerListeners() {
super.registerListeners();
gauge.currentValueProperty().addListener(currentValueListener);
}
// ******************** Methods *******************************************
@Override protected void handleEvents(final String EVENT_TYPE) {
super.handleEvents(EVENT_TYPE);
if ("RECALC".equals(EVENT_TYPE)) {
minValue = gauge.getMinValue();
maxValue = gauge.getMaxValue();
range = gauge.getRange();
angleStep = ANGLE_RANGE / range;
redraw();
setBar(gauge.getCurrentValue());
} else if ("SECTIONS".equals(EVENT_TYPE)) {
sections = gauge.getSections();
} else if ("VISIBILITY".equals(EVENT_TYPE)) {
sectionsVisible = gauge.getSectionsVisible();
thresholdVisible = gauge.isThresholdVisible();
thresholdVisible = gauge.isThresholdVisible();
}
}
@Override public void dispose() {
gauge.currentValueProperty().removeListener(currentValueListener);
super.dispose();
}
// ******************** Canvas ********************************************
private void setBar(final double VALUE) {
barCtx.clearRect(0, 0, size, size);
barCtx.setLineCap(StrokeLineCap.BUTT);
barCtx.setStroke(barColor);
barCtx.setLineWidth(barWidth);
if (sectionsVisible) {
int listSize = sections.size();
for (int i = 0 ; i < listSize ;i++) {
Section section = sections.get(i);
if (section.contains(VALUE)) {
barCtx.setStroke(section.getColor());
break;
}
}
}
if (thresholdVisible && VALUE > gauge.getThreshold()) {
barCtx.setStroke(thresholdColor);
}
double v = (VALUE - minValue) * angleStep;
int minValueAngle = (int) (-minValue * angleStep);
if (!isStartFromZero) {
for (int i = 0; i < 300; i++) {
if (i % 6 == 0 && i < v) {
barCtx.strokeArc(barWidth * 0.5 + barWidth * 0.3, barWidth * 0.5 + barWidth * 0.3, size - barWidth - barWidth * 0.6, size - barWidth - barWidth * 0.6, (-i - 125), 4.6, ArcType.OPEN);
}
}
} else {
if (Double.compare(VALUE, 0) != 0) {
if (VALUE < 0) {
for (int i = Math.min(minValueAngle, 300) - 1; i >= 0; i--) {
if (i % 6 == 0 && i > v - 6) {
barCtx.strokeArc(barWidth * 0.5 + barWidth * 0.3, barWidth * 0.5 + barWidth * 0.3, size - barWidth - barWidth * 0.6, size - barWidth - barWidth * 0.6, (-i - 125), 4.6, ArcType.OPEN);
}
}
} else {
for (int i = Math.max(minValueAngle, 0) - 3; i < 300; i++) {
if (i % 6 == 0 && i < v) {
barCtx.strokeArc(barWidth * 0.5 + barWidth * 0.3, barWidth * 0.5 + barWidth * 0.3, size - barWidth - barWidth * 0.6, size - barWidth - barWidth * 0.6, (-i - 125), 4.6, ArcType.OPEN);
}
}
}
}
}
valueText.setText(formatNumber(gauge.getLocale(), gauge.getFormatString(), gauge.getDecimals(), VALUE));
valueText.setLayoutX(valueBkgText.getLayoutBounds().getMaxX() - valueText.getLayoutBounds().getWidth());
}
private void drawBackground() {
backgroundCanvas.setCache(false);
double outerBarWidth = size * 0.006;
backgroundCtx.setLineCap(StrokeLineCap.BUTT);
backgroundCtx.clearRect(0, 0, size, size);
boolean shadowsEnabled = gauge.isShadowsEnabled();
// draw translucent background
backgroundCtx.setStroke(Color.rgb(0, 12, 6, 0.1));
Color bColor = Helper.getTranslucentColorFrom(barColor, 0.1);
for (int i = -60 ; i < 240 ; i++) {
backgroundCtx.save();
if (i % 6 == 0) {
// draw value bar
backgroundCtx.setStroke(bColor);
backgroundCtx.setLineWidth(barWidth);
backgroundCtx.strokeArc(barWidth * 0.5 + barWidth * 0.3, barWidth * 0.5 + barWidth * 0.3, size - barWidth - barWidth * 0.6, size - barWidth - barWidth * 0.6, i + 1, 4.6, ArcType.OPEN);
// draw outer bar
backgroundCtx.setStroke(barColor);
backgroundCtx.setLineWidth(outerBarWidth);
backgroundCtx.strokeArc(outerBarWidth, outerBarWidth, size - (2 * outerBarWidth), size - (2 * outerBarWidth), i + 1, 4.6, ArcType.OPEN);
}
backgroundCtx.restore();
}
// draw the title
if (!gauge.getTitle().isEmpty()) {
String title = gauge.getTitle();
char[] bkgTitleChrs = new char[title.length()];
Arrays.fill(bkgTitleChrs, '8');
backgroundCtx.setFill(shadowsEnabled ? Helper.getTranslucentColorFrom(titleColor, 0.1) : Color.TRANSPARENT);
backgroundCtx.setFont(Fonts.digitalReadoutBold(0.09 * size));
backgroundCtx.setTextBaseline(VPos.CENTER);
backgroundCtx.setTextAlign(TextAlignment.CENTER);
backgroundCtx.fillText(new String(bkgTitleChrs), center, size * 0.35, size * 0.55);
backgroundCtx.setFill(titleColor);
backgroundCtx.fillText(title, center, size * 0.35, size * 0.55);
}
// draw the subtitle
if (!gauge.getSubTitle().isEmpty()) {
String subTitle = gauge.getSubTitle();
char[] bkgSubTitleChrs = new char[subTitle.length()];
Arrays.fill(bkgSubTitleChrs, '8');
backgroundCtx.setFill(shadowsEnabled ? Helper.getTranslucentColorFrom(subTitleColor, 0.1) : Color.TRANSPARENT);
backgroundCtx.setFont(Fonts.digital(0.09 * size));
backgroundCtx.fillText(new String(bkgSubTitleChrs), center, size * 0.66);
backgroundCtx.setFill(subTitleColor);
backgroundCtx.fillText(subTitle, center, size * 0.66);
}
// draw the unit
if (!gauge.getUnit().isEmpty()) {
String unit = gauge.getUnit();
char[] bkgUnitChrs = new char[unit.length()];
Arrays.fill(bkgUnitChrs, '8');
backgroundCtx.setFill(shadowsEnabled ? Helper.getTranslucentColorFrom(unitColor, 0.1) : Color.TRANSPARENT);
backgroundCtx.setFont(Fonts.digital(0.09 * size));
backgroundCtx.fillText(new String(bkgUnitChrs), center, size * 0.88);
backgroundCtx.setFill(unitColor);
backgroundCtx.fillText(unit, center, size * 0.88);
}
// draw tick labels
drawTickMarks();
backgroundCanvas.setCache(true);
backgroundCanvas.setCacheHint(CacheHint.QUALITY);
// draw the value
if (gauge.isValueVisible()) {
StringBuilder valueBkg = new StringBuilder();
int len = String.valueOf((int) gauge.getMaxValue()).length();
if (gauge.getMinValue() < 0) { len++; }
for (int i = 0 ; i < len ; i++) { valueBkg.append("8"); }
if (gauge.getDecimals() > 0) {
valueBkg.append(".");
len = gauge.getDecimals();
for (int i = 0 ; i < len ; i++) { valueBkg.append("8"); }
}
valueBkgText.setText(valueBkg.toString());
valueBkgText.setX((size - valueBkgText.getLayoutBounds().getWidth()) * 0.5);
}
}
private void drawTickMarks() {
double sinValue;
double cosValue;
double centerX = center;
double centerY = center;
int tickLabelDecimals = gauge.getTickLabelDecimals();
String tickLabelFormatString = "%." + tickLabelDecimals + "f";
double minorTickSpace = gauge.getMinorTickSpace();
double tmpAngleStep = angleStep * minorTickSpace;
BigDecimal minorTickSpaceBD = BigDecimal.valueOf(minorTickSpace);
BigDecimal majorTickSpaceBD = BigDecimal.valueOf(gauge.getMajorTickSpace());
BigDecimal counterBD = BigDecimal.valueOf(minValue);
double counter = minValue;
Color tickMarkColor = gauge.getTickMarkColor();
Color majorTickMarkColor = gauge.getMajorTickMarkColor().equals(tickMarkColor) ? tickMarkColor : gauge.getMajorTickMarkColor();
Color tickLabelColor = gauge.getTickLabelColor();
Color zeroColor = gauge.getZeroColor();
boolean isNotZero = true;
boolean majorTickMarksVisible = gauge.getMajorTickMarksVisible();
boolean tickLabelsVisible = gauge.getTickLabelsVisible();
boolean onlyFirstAndLastLabelVisible = gauge.isOnlyFirstAndLastTickLabelVisible();
double customFontSizeFactor = gauge.getCustomTickLabelFontSize() / 400;
boolean fullRange = (minValue < 0 && maxValue > 0);
double tickLabelOrientationFactor = 0.8;
double tickLabelFontSize = tickLabelDecimals == 0 ? 0.051 * size : 0.048 * size;
tickLabelFontSize = gauge.getCustomTickLabelsEnabled() ? customFontSizeFactor * size : tickLabelFontSize;
Font tickLabelFont = Fonts.robotoCondensedRegular(tickLabelFontSize * tickLabelOrientationFactor);
Font tickLabelZeroFont = fullRange ? Fonts.robotoCondensedBold(tickLabelFontSize * tickLabelOrientationFactor) : tickLabelFont;
// Variables needed for tickmarks
double innerPointX;
double innerPointY;
double triangleOuterAngle1;
double triangleOuterAngle2;
double triangleOuterPoint1X;
double triangleOuterPoint1Y;
double triangleOuterPoint2X;
double triangleOuterPoint2Y;
double textPointX;
double textPointY;
backgroundCtx.setStroke(tickMarkColor);
backgroundCtx.strokeArc(0.0875 * size, 0.0875 * size, 0.825 * size, 0.825 * size, 300, 300, ArcType.OPEN);
// Main loop
BigDecimal tmpStepBD = new BigDecimal(tmpAngleStep);
tmpStepBD = tmpStepBD.setScale(3, BigDecimal.ROUND_HALF_UP);
double tmpStep = tmpStepBD.doubleValue();
double angle = 0;
for (double i = 0 ; Double.compare(-ANGLE_RANGE - tmpStep, i) <= 0 ; i -= tmpStep) {
sinValue = Math.sin(Math.toRadians(angle + START_ANGLE));
cosValue = Math.cos(Math.toRadians(angle + START_ANGLE));
innerPointX = centerX + size * 0.395 * sinValue;
innerPointY = centerY + size * 0.395 * cosValue;
triangleOuterAngle1 = Math.toRadians(angle - 1.2 + START_ANGLE);
triangleOuterAngle2 = Math.toRadians(angle + 1.2 + START_ANGLE);
triangleOuterPoint1X = centerX + size * 0.4125 * Math.sin(triangleOuterAngle1);
triangleOuterPoint1Y = centerY + size * 0.4125 * Math.cos(triangleOuterAngle1);
triangleOuterPoint2X = centerX + size * 0.4125 * Math.sin(triangleOuterAngle2);
triangleOuterPoint2Y = centerY + size * 0.4125 * Math.cos(triangleOuterAngle2);
textPointX = centerX + size * 0.365 * sinValue;
textPointY = centerY + size * 0.365 * cosValue;
// Set the general tickmark color
backgroundCtx.setStroke(tickMarkColor);
backgroundCtx.setFill(tickMarkColor);
backgroundCtx.setLineCap(StrokeLineCap.BUTT);
if (Double.compare(counterBD.remainder(majorTickSpaceBD).doubleValue(), 0.0) == 0) {
isNotZero = Double.compare(0.0, counter) != 0;
if (majorTickMarksVisible) {
backgroundCtx.setFill(majorTickMarkColor);
backgroundCtx.setStroke(majorTickMarkColor);
backgroundCtx.setLineWidth(size * 0.0055);
backgroundCtx.setLineCap(StrokeLineCap.BUTT);
}
if (fullRange && !isNotZero) {
backgroundCtx.setFill(zeroColor);
backgroundCtx.setStroke(zeroColor);
}
if (majorTickMarksVisible) {
Helper.drawTriangle(backgroundCtx, innerPointX, innerPointY, triangleOuterPoint1X, triangleOuterPoint1Y, triangleOuterPoint2X, triangleOuterPoint2Y);
}
// Draw tick label text
if (tickLabelsVisible) {
backgroundCtx.save();
backgroundCtx.translate(textPointX, textPointY);
Helper.rotateContextForText(backgroundCtx, START_ANGLE, angle, TickLabelOrientation.HORIZONTAL);
backgroundCtx.setFont(isNotZero ? tickLabelFont : tickLabelZeroFont);
backgroundCtx.setTextAlign(TextAlignment.CENTER);
backgroundCtx.setTextBaseline(VPos.CENTER);
if (!onlyFirstAndLastLabelVisible) {
if (isNotZero) {
backgroundCtx.setFill(tickLabelColor);
} else {
backgroundCtx.setFill(fullRange ? zeroColor : tickLabelColor);
}
} else {
if ((Double.compare(counter, minValue) == 0 || Double.compare(counter, maxValue) == 0)) {
if (isNotZero) {
backgroundCtx.setFill(tickLabelColor);
} else {
backgroundCtx.setFill(fullRange ? zeroColor : tickLabelColor);
}
} else {
backgroundCtx.setFill(Color.TRANSPARENT);
}
}
backgroundCtx.fillText(String.format(locale, tickLabelFormatString, counter), 0, 0);
backgroundCtx.restore();
}
}
counterBD = counterBD.add(minorTickSpaceBD);
counter = counterBD.doubleValue();
if (counter > maxValue) break;
angle = (angle - tmpAngleStep);
}
}
// ******************** Resizing ******************************************
@Override protected void resize() {
double width = gauge.getWidth() - gauge.getInsets().getLeft() - gauge.getInsets().getRight();
double height = gauge.getHeight() - gauge.getInsets().getTop() - gauge.getInsets().getBottom();
size = width < height ? width : height;
if (width > 0 && height > 0) {
pane.setMaxSize(size, size);
pane.relocate((width - size) * 0.5, (height - size) * 0.5);
center = size * 0.5;
barWidth = size * 0.06;
backgroundCanvas.setWidth(size);
backgroundCanvas.setHeight(size);
barCanvas.setWidth(size);
barCanvas.setHeight(size);
valueBkgText.setFont(Fonts.digital(0.18 * size));
valueBkgText.setY(center + (valueBkgText.getLayoutBounds().getHeight() * 0.5));
valueText.setFont(Fonts.digital(0.18 * size));
valueText.setY(center + (valueText.getLayoutBounds().getHeight() * 0.5));
drawBackground();
setBar(gauge.getCurrentValue());
}
}
@Override protected void redraw() {
pane.setBackground(new Background(new BackgroundFill(gauge.getBackgroundPaint(), new CornerRadii(1024), Insets.EMPTY)));
pane.setBorder(new Border(new BorderStroke(gauge.getBorderPaint(), BorderStrokeStyle.SOLID, new CornerRadii(1024), new BorderWidths(gauge.getBorderWidth() / PREFERRED_WIDTH * size))));
locale = gauge.getLocale();
barColor = gauge.getBarColor();
valueColor = gauge.getValueColor();
titleColor = gauge.getTitleColor();
subTitleColor = gauge.getSubTitleColor();
unitColor = gauge.getUnitColor();
sectionsVisible = gauge.getSectionsVisible();
drawBackground();
setBar(gauge.getCurrentValue());
valueBkgText.setFill(gauge.isShadowsEnabled() ? Helper.getTranslucentColorFrom(valueColor, 0.1) : Color.TRANSPARENT);
valueText.setFill(valueColor);
}
}
| /*
* Copyright (c) 2016 by <NAME>
*
* 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 eu.hansolo.medusa.IMPORT_0;
import eu.hansolo.medusa.Fonts;
import eu.hansolo.medusa.IMPORT_1;
import eu.hansolo.medusa.Section;
import eu.hansolo.medusa.IMPORT_2;
import eu.hansolo.medusa.tools.IMPORT_3;
import IMPORT_4.IMPORT_5.IMPORT_6;
import IMPORT_4.IMPORT_7.IMPORT_8;
import IMPORT_4.IMPORT_7.List;
import IMPORT_4.IMPORT_7.Locale;
import javafx.beans.IMPORT_9;
import javafx.IMPORT_10.IMPORT_11;
import javafx.IMPORT_10.IMPORT_12;
import javafx.scene.IMPORT_13;
import javafx.scene.canvas.IMPORT_14;
import javafx.scene.canvas.IMPORT_15;
import javafx.scene.layout.IMPORT_16;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.IMPORT_17;
import javafx.scene.layout.IMPORT_18;
import javafx.scene.layout.IMPORT_19;
import javafx.scene.layout.BorderWidths;
import javafx.scene.layout.IMPORT_20;
import javafx.scene.layout.IMPORT_21;
import javafx.scene.IMPORT_22.Color;
import javafx.scene.IMPORT_23.ArcType;
import javafx.scene.IMPORT_23.IMPORT_24;
import javafx.scene.IMPORT_25.IMPORT_26;
import javafx.scene.IMPORT_25.Text;
import javafx.scene.IMPORT_25.TextAlignment;
import static eu.hansolo.medusa.tools.IMPORT_3.formatNumber;
/**
* Created by hansolo on 08.02.16.
*/
public class CLASS_0 extends CLASS_1 {
private static final double VAR_0 = -30;
private static final double ANGLE_RANGE = 300;
private double size;
private double VAR_1;
private IMPORT_21 pane;
private IMPORT_14 VAR_2;
private IMPORT_15 VAR_3;
private IMPORT_14 VAR_4;
private IMPORT_15 VAR_5;
private Text valueBkgText;
private Text VAR_6;
private Color VAR_7;
private Color VAR_8;
private Color VAR_9;
private Color VAR_10;
private Color VAR_11;
private double minValue;
private double VAR_12;
private double VAR_13;
private double VAR_14;
private boolean VAR_15;
private double VAR_16;
private Locale VAR_17;
private boolean VAR_18;
private List<Section> sections;
private boolean thresholdVisible;
private Color VAR_19;
private IMPORT_9 currentValueListener;
// ******************** Constructors **************************************
public CLASS_0(IMPORT_1 gauge) {
super(gauge);
if (gauge.FUNC_1()) gauge.FUNC_2();
minValue = gauge.FUNC_3();
VAR_12 = gauge.getMaxValue();
VAR_13 = gauge.getRange();
VAR_14 = ANGLE_RANGE / VAR_13;
VAR_17 = gauge.getLocale();
VAR_7 = gauge.getBarColor();
VAR_8 = gauge.FUNC_4();
VAR_9 = gauge.FUNC_5();
VAR_10 = gauge.getSubTitleColor();
VAR_11 = gauge.getUnitColor();
VAR_15 = gauge.FUNC_0();
VAR_18 = gauge.getSectionsVisible();
sections = gauge.FUNC_6();
thresholdVisible = gauge.FUNC_7();
VAR_19 = gauge.FUNC_8();
currentValueListener = VAR_20 -> setBar(gauge.FUNC_9());
initGraphics();
FUNC_10();
setBar(gauge.FUNC_9());
}
// ******************** Initialization ************************************
private void initGraphics() {
// Set initial size
if (VAR_21.compare(gauge.getPrefWidth(), 0.0) <= 0 || VAR_21.compare(gauge.getPrefHeight(), 0.0) <= 0 ||
VAR_21.compare(gauge.FUNC_11(), 0.0) <= 0 || VAR_21.compare(gauge.FUNC_12(), 0.0) <= 0) {
if (gauge.getPrefWidth() > 0 && gauge.getPrefHeight() > 0) {
gauge.setPrefSize(gauge.getPrefWidth(), gauge.getPrefHeight());
} else {
gauge.setPrefSize(VAR_22, PREFERRED_HEIGHT);
}
}
VAR_2 = new IMPORT_14(VAR_22, PREFERRED_HEIGHT);
VAR_3 = VAR_2.getGraphicsContext2D();
VAR_4 = new IMPORT_14(VAR_22, PREFERRED_HEIGHT);
VAR_5 = VAR_4.getGraphicsContext2D();
valueBkgText = new Text();
valueBkgText.FUNC_13(null);
valueBkgText.setFill(IMPORT_3.getTranslucentColorFrom(VAR_8, 0.1));
VAR_6 = new Text();
VAR_6.FUNC_13(null);
VAR_6.setFill(VAR_8);
IMPORT_3.enableNode(VAR_6, gauge.isValueVisible());
pane = new IMPORT_21(VAR_2, VAR_4, valueBkgText, VAR_6);
pane.FUNC_14(new IMPORT_16(new BackgroundFill(gauge.FUNC_15(), new IMPORT_20(1024), IMPORT_11.EMPTY)));
pane.setBorder(new IMPORT_17(new IMPORT_18(gauge.FUNC_16(), IMPORT_19.VAR_23, new IMPORT_20(1024), new BorderWidths(gauge.getBorderWidth()))));
getChildren().setAll(pane);
}
@Override protected void FUNC_10() {
super.FUNC_10();
gauge.FUNC_17().addListener(currentValueListener);
}
// ******************** Methods *******************************************
@Override protected void FUNC_18(final String VAR_24) {
super.FUNC_18(VAR_24);
if ("RECALC".FUNC_19(VAR_24)) {
minValue = gauge.FUNC_3();
VAR_12 = gauge.getMaxValue();
VAR_13 = gauge.getRange();
VAR_14 = ANGLE_RANGE / VAR_13;
FUNC_20();
setBar(gauge.FUNC_9());
} else if ("SECTIONS".FUNC_19(VAR_24)) {
sections = gauge.FUNC_6();
} else if ("VISIBILITY".FUNC_19(VAR_24)) {
VAR_18 = gauge.getSectionsVisible();
thresholdVisible = gauge.FUNC_7();
thresholdVisible = gauge.FUNC_7();
}
}
@Override public void FUNC_21() {
gauge.FUNC_17().removeListener(currentValueListener);
super.FUNC_21();
}
// ******************** Canvas ********************************************
private void setBar(final double VAR_25) {
VAR_5.FUNC_22(0, 0, size, size);
VAR_5.FUNC_23(IMPORT_24.BUTT);
VAR_5.FUNC_13(VAR_7);
VAR_5.setLineWidth(VAR_16);
if (VAR_18) {
int VAR_26 = sections.size();
for (int i = 0 ; i < VAR_26 ;i++) {
Section VAR_27 = sections.FUNC_24(i);
if (VAR_27.FUNC_25(VAR_25)) {
VAR_5.FUNC_13(VAR_27.FUNC_26());
break;
}
}
}
if (thresholdVisible && VAR_25 > gauge.getThreshold()) {
VAR_5.FUNC_13(VAR_19);
}
double VAR_28 = (VAR_25 - minValue) * VAR_14;
int VAR_29 = (int) (-minValue * VAR_14);
if (!VAR_15) {
for (int i = 0; i < 300; i++) {
if (i % 6 == 0 && i < VAR_28) {
VAR_5.FUNC_27(VAR_16 * 0.5 + VAR_16 * 0.3, VAR_16 * 0.5 + VAR_16 * 0.3, size - VAR_16 - VAR_16 * 0.6, size - VAR_16 - VAR_16 * 0.6, (-i - 125), 4.6, ArcType.VAR_30);
}
}
} else {
if (VAR_21.compare(VAR_25, 0) != 0) {
if (VAR_25 < 0) {
for (int i = VAR_31.FUNC_28(VAR_29, 300) - 1; i >= 0; i--) {
if (i % 6 == 0 && i > VAR_28 - 6) {
VAR_5.FUNC_27(VAR_16 * 0.5 + VAR_16 * 0.3, VAR_16 * 0.5 + VAR_16 * 0.3, size - VAR_16 - VAR_16 * 0.6, size - VAR_16 - VAR_16 * 0.6, (-i - 125), 4.6, ArcType.VAR_30);
}
}
} else {
for (int i = VAR_31.FUNC_29(VAR_29, 0) - 3; i < 300; i++) {
if (i % 6 == 0 && i < VAR_28) {
VAR_5.FUNC_27(VAR_16 * 0.5 + VAR_16 * 0.3, VAR_16 * 0.5 + VAR_16 * 0.3, size - VAR_16 - VAR_16 * 0.6, size - VAR_16 - VAR_16 * 0.6, (-i - 125), 4.6, ArcType.VAR_30);
}
}
}
}
}
VAR_6.setText(formatNumber(gauge.getLocale(), gauge.getFormatString(), gauge.FUNC_30(), VAR_25));
VAR_6.FUNC_31(valueBkgText.getLayoutBounds().FUNC_32() - VAR_6.getLayoutBounds().FUNC_11());
}
private void FUNC_33() {
VAR_2.setCache(false);
double VAR_32 = size * 0.006;
VAR_3.FUNC_23(IMPORT_24.BUTT);
VAR_3.FUNC_22(0, 0, size, size);
boolean VAR_33 = gauge.FUNC_34();
// draw translucent background
VAR_3.FUNC_13(Color.rgb(0, 12, 6, 0.1));
Color VAR_34 = IMPORT_3.getTranslucentColorFrom(VAR_7, 0.1);
for (int i = -60 ; i < 240 ; i++) {
VAR_3.save();
if (i % 6 == 0) {
// draw value bar
VAR_3.FUNC_13(VAR_34);
VAR_3.setLineWidth(VAR_16);
VAR_3.FUNC_27(VAR_16 * 0.5 + VAR_16 * 0.3, VAR_16 * 0.5 + VAR_16 * 0.3, size - VAR_16 - VAR_16 * 0.6, size - VAR_16 - VAR_16 * 0.6, i + 1, 4.6, ArcType.VAR_30);
// draw outer bar
VAR_3.FUNC_13(VAR_7);
VAR_3.setLineWidth(VAR_32);
VAR_3.FUNC_27(VAR_32, VAR_32, size - (2 * VAR_32), size - (2 * VAR_32), i + 1, 4.6, ArcType.VAR_30);
}
VAR_3.FUNC_35();
}
// draw the title
if (!gauge.FUNC_36().FUNC_37()) {
String VAR_35 = gauge.FUNC_36();
char[] bkgTitleChrs = new char[VAR_35.FUNC_38()];
IMPORT_8.FUNC_39(bkgTitleChrs, '8');
VAR_3.setFill(VAR_33 ? IMPORT_3.getTranslucentColorFrom(VAR_9, 0.1) : Color.TRANSPARENT);
VAR_3.FUNC_40(Fonts.digitalReadoutBold(0.09 * size));
VAR_3.setTextBaseline(IMPORT_12.VAR_36);
VAR_3.FUNC_41(TextAlignment.VAR_36);
VAR_3.FUNC_42(new String(bkgTitleChrs), VAR_1, size * 0.35, size * 0.55);
VAR_3.setFill(VAR_9);
VAR_3.FUNC_42(VAR_35, VAR_1, size * 0.35, size * 0.55);
}
// draw the subtitle
if (!gauge.getSubTitle().FUNC_37()) {
String VAR_37 = gauge.getSubTitle();
char[] VAR_38 = new char[VAR_37.FUNC_38()];
IMPORT_8.FUNC_39(VAR_38, '8');
VAR_3.setFill(VAR_33 ? IMPORT_3.getTranslucentColorFrom(VAR_10, 0.1) : Color.TRANSPARENT);
VAR_3.FUNC_40(Fonts.digital(0.09 * size));
VAR_3.FUNC_42(new String(VAR_38), VAR_1, size * 0.66);
VAR_3.setFill(VAR_10);
VAR_3.FUNC_42(VAR_37, VAR_1, size * 0.66);
}
// draw the unit
if (!gauge.getUnit().FUNC_37()) {
String unit = gauge.getUnit();
char[] VAR_39 = new char[unit.FUNC_38()];
IMPORT_8.FUNC_39(VAR_39, '8');
VAR_3.setFill(VAR_33 ? IMPORT_3.getTranslucentColorFrom(VAR_11, 0.1) : Color.TRANSPARENT);
VAR_3.FUNC_40(Fonts.digital(0.09 * size));
VAR_3.FUNC_42(new String(VAR_39), VAR_1, size * 0.88);
VAR_3.setFill(VAR_11);
VAR_3.FUNC_42(unit, VAR_1, size * 0.88);
}
// draw tick labels
FUNC_43();
VAR_2.setCache(true);
VAR_2.FUNC_44(IMPORT_13.VAR_40);
// draw the value
if (gauge.isValueVisible()) {
CLASS_2 valueBkg = new CLASS_2();
int VAR_41 = String.FUNC_45((int) gauge.getMaxValue()).FUNC_38();
if (gauge.FUNC_3() < 0) { VAR_41++; }
for (int i = 0 ; i < VAR_41 ; i++) { valueBkg.FUNC_46("8"); }
if (gauge.FUNC_30() > 0) {
valueBkg.FUNC_46(".");
VAR_41 = gauge.FUNC_30();
for (int i = 0 ; i < VAR_41 ; i++) { valueBkg.FUNC_46("8"); }
}
valueBkgText.setText(valueBkg.toString());
valueBkgText.setX((size - valueBkgText.getLayoutBounds().FUNC_11()) * 0.5);
}
}
private void FUNC_43() {
double VAR_42;
double VAR_43;
double centerX = VAR_1;
double VAR_44 = VAR_1;
int VAR_45 = gauge.getTickLabelDecimals();
String VAR_46 = "%." + VAR_45 + "f";
double VAR_47 = gauge.FUNC_47();
double VAR_48 = VAR_14 * VAR_47;
IMPORT_6 VAR_49 = IMPORT_6.FUNC_45(VAR_47);
IMPORT_6 VAR_50 = IMPORT_6.FUNC_45(gauge.getMajorTickSpace());
IMPORT_6 counterBD = IMPORT_6.FUNC_45(minValue);
double VAR_51 = minValue;
Color VAR_52 = gauge.FUNC_48();
Color majorTickMarkColor = gauge.getMajorTickMarkColor().FUNC_19(VAR_52) ? VAR_52 : gauge.getMajorTickMarkColor();
Color VAR_53 = gauge.FUNC_49();
Color VAR_54 = gauge.getZeroColor();
boolean VAR_55 = true;
boolean majorTickMarksVisible = gauge.FUNC_50();
boolean tickLabelsVisible = gauge.FUNC_51();
boolean VAR_56 = gauge.isOnlyFirstAndLastTickLabelVisible();
double VAR_57 = gauge.FUNC_52() / 400;
boolean VAR_58 = (minValue < 0 && VAR_12 > 0);
double VAR_59 = 0.8;
double VAR_60 = VAR_45 == 0 ? 0.051 * size : 0.048 * size;
VAR_60 = gauge.getCustomTickLabelsEnabled() ? VAR_57 * size : VAR_60;
IMPORT_26 tickLabelFont = Fonts.robotoCondensedRegular(VAR_60 * VAR_59);
IMPORT_26 VAR_61 = VAR_58 ? Fonts.FUNC_53(VAR_60 * VAR_59) : tickLabelFont;
// Variables needed for tickmarks
double innerPointX;
double innerPointY;
double VAR_62;
double triangleOuterAngle2;
double triangleOuterPoint1X;
double VAR_63;
double triangleOuterPoint2X;
double triangleOuterPoint2Y;
double textPointX;
double VAR_64;
VAR_3.FUNC_13(VAR_52);
VAR_3.FUNC_27(0.0875 * size, 0.0875 * size, 0.825 * size, 0.825 * size, 300, 300, ArcType.VAR_30);
// Main loop
IMPORT_6 VAR_65 = new IMPORT_6(VAR_48);
VAR_65 = VAR_65.setScale(3, IMPORT_6.VAR_66);
double tmpStep = VAR_65.doubleValue();
double angle = 0;
for (double i = 0 ; VAR_21.compare(-ANGLE_RANGE - tmpStep, i) <= 0 ; i -= tmpStep) {
VAR_42 = VAR_31.FUNC_54(VAR_31.FUNC_55(angle + VAR_0));
VAR_43 = VAR_31.cos(VAR_31.FUNC_55(angle + VAR_0));
innerPointX = centerX + size * 0.395 * VAR_42;
innerPointY = VAR_44 + size * 0.395 * VAR_43;
VAR_62 = VAR_31.FUNC_55(angle - 1.2 + VAR_0);
triangleOuterAngle2 = VAR_31.FUNC_55(angle + 1.2 + VAR_0);
triangleOuterPoint1X = centerX + size * 0.4125 * VAR_31.FUNC_54(VAR_62);
VAR_63 = VAR_44 + size * 0.4125 * VAR_31.cos(VAR_62);
triangleOuterPoint2X = centerX + size * 0.4125 * VAR_31.FUNC_54(triangleOuterAngle2);
triangleOuterPoint2Y = VAR_44 + size * 0.4125 * VAR_31.cos(triangleOuterAngle2);
textPointX = centerX + size * 0.365 * VAR_42;
VAR_64 = VAR_44 + size * 0.365 * VAR_43;
// Set the general tickmark color
VAR_3.FUNC_13(VAR_52);
VAR_3.setFill(VAR_52);
VAR_3.FUNC_23(IMPORT_24.BUTT);
if (VAR_21.compare(counterBD.remainder(VAR_50).doubleValue(), 0.0) == 0) {
VAR_55 = VAR_21.compare(0.0, VAR_51) != 0;
if (majorTickMarksVisible) {
VAR_3.setFill(majorTickMarkColor);
VAR_3.FUNC_13(majorTickMarkColor);
VAR_3.setLineWidth(size * 0.0055);
VAR_3.FUNC_23(IMPORT_24.BUTT);
}
if (VAR_58 && !VAR_55) {
VAR_3.setFill(VAR_54);
VAR_3.FUNC_13(VAR_54);
}
if (majorTickMarksVisible) {
IMPORT_3.drawTriangle(VAR_3, innerPointX, innerPointY, triangleOuterPoint1X, VAR_63, triangleOuterPoint2X, triangleOuterPoint2Y);
}
// Draw tick label text
if (tickLabelsVisible) {
VAR_3.save();
VAR_3.FUNC_56(textPointX, VAR_64);
IMPORT_3.FUNC_57(VAR_3, VAR_0, angle, IMPORT_2.HORIZONTAL);
VAR_3.FUNC_40(VAR_55 ? tickLabelFont : VAR_61);
VAR_3.FUNC_41(TextAlignment.VAR_36);
VAR_3.setTextBaseline(IMPORT_12.VAR_36);
if (!VAR_56) {
if (VAR_55) {
VAR_3.setFill(VAR_53);
} else {
VAR_3.setFill(VAR_58 ? VAR_54 : VAR_53);
}
} else {
if ((VAR_21.compare(VAR_51, minValue) == 0 || VAR_21.compare(VAR_51, VAR_12) == 0)) {
if (VAR_55) {
VAR_3.setFill(VAR_53);
} else {
VAR_3.setFill(VAR_58 ? VAR_54 : VAR_53);
}
} else {
VAR_3.setFill(Color.TRANSPARENT);
}
}
VAR_3.FUNC_42(String.format(VAR_17, VAR_46, VAR_51), 0, 0);
VAR_3.FUNC_35();
}
}
counterBD = counterBD.FUNC_58(VAR_49);
VAR_51 = counterBD.doubleValue();
if (VAR_51 > VAR_12) break;
angle = (angle - VAR_48);
}
}
// ******************** Resizing ******************************************
@Override protected void resize() {
double VAR_67 = gauge.FUNC_11() - gauge.FUNC_59().getLeft() - gauge.FUNC_59().FUNC_60();
double height = gauge.FUNC_12() - gauge.FUNC_59().FUNC_61() - gauge.FUNC_59().FUNC_62();
size = VAR_67 < height ? VAR_67 : height;
if (VAR_67 > 0 && height > 0) {
pane.setMaxSize(size, size);
pane.relocate((VAR_67 - size) * 0.5, (height - size) * 0.5);
VAR_1 = size * 0.5;
VAR_16 = size * 0.06;
VAR_2.FUNC_63(size);
VAR_2.FUNC_64(size);
VAR_4.FUNC_63(size);
VAR_4.FUNC_64(size);
valueBkgText.FUNC_40(Fonts.digital(0.18 * size));
valueBkgText.FUNC_65(VAR_1 + (valueBkgText.getLayoutBounds().FUNC_12() * 0.5));
VAR_6.FUNC_40(Fonts.digital(0.18 * size));
VAR_6.FUNC_65(VAR_1 + (VAR_6.getLayoutBounds().FUNC_12() * 0.5));
FUNC_33();
setBar(gauge.FUNC_9());
}
}
@Override protected void FUNC_20() {
pane.FUNC_14(new IMPORT_16(new BackgroundFill(gauge.FUNC_15(), new IMPORT_20(1024), IMPORT_11.EMPTY)));
pane.setBorder(new IMPORT_17(new IMPORT_18(gauge.FUNC_16(), IMPORT_19.VAR_23, new IMPORT_20(1024), new BorderWidths(gauge.getBorderWidth() / VAR_22 * size))));
VAR_17 = gauge.getLocale();
VAR_7 = gauge.getBarColor();
VAR_8 = gauge.FUNC_4();
VAR_9 = gauge.FUNC_5();
VAR_10 = gauge.getSubTitleColor();
VAR_11 = gauge.getUnitColor();
VAR_18 = gauge.getSectionsVisible();
FUNC_33();
setBar(gauge.FUNC_9());
valueBkgText.setFill(gauge.FUNC_34() ? IMPORT_3.getTranslucentColorFrom(VAR_8, 0.1) : Color.TRANSPARENT);
VAR_6.setFill(VAR_8);
}
}
| 0.642584 | {'IMPORT_0': 'skins', 'IMPORT_1': 'Gauge', 'IMPORT_2': 'TickLabelOrientation', 'IMPORT_3': 'Helper', 'IMPORT_4': 'java', 'IMPORT_5': 'math', 'IMPORT_6': 'BigDecimal', 'IMPORT_7': 'util', 'IMPORT_8': 'Arrays', 'IMPORT_9': 'InvalidationListener', 'IMPORT_10': 'geometry', 'IMPORT_11': 'Insets', 'IMPORT_12': 'VPos', 'IMPORT_13': 'CacheHint', 'IMPORT_14': 'Canvas', 'IMPORT_15': 'GraphicsContext', 'IMPORT_16': 'Background', 'IMPORT_17': 'Border', 'IMPORT_18': 'BorderStroke', 'IMPORT_19': 'BorderStrokeStyle', 'IMPORT_20': 'CornerRadii', 'IMPORT_21': 'Pane', 'IMPORT_22': 'paint', 'IMPORT_23': 'shape', 'IMPORT_24': 'StrokeLineCap', 'IMPORT_25': 'text', 'IMPORT_26': 'Font', 'CLASS_0': 'DigitalSkin', 'CLASS_1': 'GaugeSkinBase', 'VAR_0': 'START_ANGLE', 'VAR_1': 'center', 'VAR_2': 'backgroundCanvas', 'VAR_3': 'backgroundCtx', 'VAR_4': 'barCanvas', 'VAR_5': 'barCtx', 'VAR_6': 'valueText', 'VAR_7': 'barColor', 'VAR_8': 'valueColor', 'VAR_9': 'titleColor', 'VAR_10': 'subTitleColor', 'VAR_11': 'unitColor', 'VAR_12': 'maxValue', 'VAR_13': 'range', 'VAR_14': 'angleStep', 'VAR_15': 'isStartFromZero', 'FUNC_0': 'isStartFromZero', 'VAR_16': 'barWidth', 'VAR_17': 'locale', 'VAR_18': 'sectionsVisible', 'VAR_19': 'thresholdColor', 'FUNC_1': 'isAutoScale', 'FUNC_2': 'calcAutoScale', 'FUNC_3': 'getMinValue', 'FUNC_4': 'getValueColor', 'FUNC_5': 'getTitleColor', 'FUNC_6': 'getSections', 'FUNC_7': 'isThresholdVisible', 'FUNC_8': 'getThresholdColor', 'VAR_20': 'o', 'FUNC_9': 'getCurrentValue', 'FUNC_10': 'registerListeners', 'VAR_21': 'Double', 'FUNC_11': 'getWidth', 'FUNC_12': 'getHeight', 'VAR_22': 'PREFERRED_WIDTH', 'FUNC_13': 'setStroke', 'FUNC_14': 'setBackground', 'FUNC_15': 'getBackgroundPaint', 'FUNC_16': 'getBorderPaint', 'VAR_23': 'SOLID', 'FUNC_17': 'currentValueProperty', 'FUNC_18': 'handleEvents', 'VAR_24': 'EVENT_TYPE', 'FUNC_19': 'equals', 'FUNC_20': 'redraw', 'FUNC_21': 'dispose', 'VAR_25': 'VALUE', 'FUNC_22': 'clearRect', 'FUNC_23': 'setLineCap', 'VAR_26': 'listSize', 'VAR_27': 'section', 'FUNC_24': 'get', 'FUNC_25': 'contains', 'FUNC_26': 'getColor', 'VAR_28': 'v', 'VAR_29': 'minValueAngle', 'FUNC_27': 'strokeArc', 'VAR_30': 'OPEN', 'VAR_31': 'Math', 'FUNC_28': 'min', 'FUNC_29': 'max', 'FUNC_30': 'getDecimals', 'FUNC_31': 'setLayoutX', 'FUNC_32': 'getMaxX', 'FUNC_33': 'drawBackground', 'VAR_32': 'outerBarWidth', 'VAR_33': 'shadowsEnabled', 'FUNC_34': 'isShadowsEnabled', 'VAR_34': 'bColor', 'FUNC_35': 'restore', 'FUNC_36': 'getTitle', 'FUNC_37': 'isEmpty', 'VAR_35': 'title', 'FUNC_38': 'length', 'FUNC_39': 'fill', 'FUNC_40': 'setFont', 'VAR_36': 'CENTER', 'FUNC_41': 'setTextAlign', 'FUNC_42': 'fillText', 'VAR_37': 'subTitle', 'VAR_38': 'bkgSubTitleChrs', 'VAR_39': 'bkgUnitChrs', 'FUNC_43': 'drawTickMarks', 'FUNC_44': 'setCacheHint', 'VAR_40': 'QUALITY', 'CLASS_2': 'StringBuilder', 'VAR_41': 'len', 'FUNC_45': 'valueOf', 'FUNC_46': 'append', 'VAR_42': 'sinValue', 'VAR_43': 'cosValue', 'VAR_44': 'centerY', 'VAR_45': 'tickLabelDecimals', 'VAR_46': 'tickLabelFormatString', 'VAR_47': 'minorTickSpace', 'FUNC_47': 'getMinorTickSpace', 'VAR_48': 'tmpAngleStep', 'VAR_49': 'minorTickSpaceBD', 'VAR_50': 'majorTickSpaceBD', 'VAR_51': 'counter', 'VAR_52': 'tickMarkColor', 'FUNC_48': 'getTickMarkColor', 'VAR_53': 'tickLabelColor', 'FUNC_49': 'getTickLabelColor', 'VAR_54': 'zeroColor', 'VAR_55': 'isNotZero', 'FUNC_50': 'getMajorTickMarksVisible', 'FUNC_51': 'getTickLabelsVisible', 'VAR_56': 'onlyFirstAndLastLabelVisible', 'VAR_57': 'customFontSizeFactor', 'FUNC_52': 'getCustomTickLabelFontSize', 'VAR_58': 'fullRange', 'VAR_59': 'tickLabelOrientationFactor', 'VAR_60': 'tickLabelFontSize', 'VAR_61': 'tickLabelZeroFont', 'FUNC_53': 'robotoCondensedBold', 'VAR_62': 'triangleOuterAngle1', 'VAR_63': 'triangleOuterPoint1Y', 'VAR_64': 'textPointY', 'VAR_65': 'tmpStepBD', 'VAR_66': 'ROUND_HALF_UP', 'FUNC_54': 'sin', 'FUNC_55': 'toRadians', 'FUNC_56': 'translate', 'FUNC_57': 'rotateContextForText', 'FUNC_58': 'add', 'VAR_67': 'width', 'FUNC_59': 'getInsets', 'FUNC_60': 'getRight', 'FUNC_61': 'getTop', 'FUNC_62': 'getBottom', 'FUNC_63': 'setWidth', 'FUNC_64': 'setHeight', 'FUNC_65': 'setY'} | java | Hibrido | 14.18% |
package neureka.backend.standard.operations.linear;
import neureka.Neureka;
import neureka.backend.api.operations.AbstractOperation;
import neureka.backend.api.operations.OperationBuilder;
import neureka.backend.standard.algorithms.Convolution;
import neureka.backend.standard.implementations.CLImplementation;
import neureka.backend.standard.implementations.HostImplementation;
import neureka.backend.standard.operations.ConvUtil;
import neureka.calculus.Function;
import neureka.calculus.args.Arg;
import neureka.devices.host.HostCPU;
import neureka.devices.opencl.OpenCLDevice;
public class XConv extends AbstractOperation
{
public XConv()
{
super(
new OperationBuilder()
.setFunction( "mul_conv" )
.setOperator( "x" )
.setArity( 2 )
.setIsOperator( true )
.setIsIndexer( false )
.setIsDifferentiable( true )
.setIsInline( false )
);
DefaultOperatorCreator<TertiaryNDIConsumer> convolutionNDICreator =
( inputs, d ) -> {
double[] t1_val = inputs[ 1 ].value64();
double[] t2_val = inputs[ 2 ].value64();
if ( d < 0 ) {
return ( t0Idx, t1Idx, t2Idx ) -> t1_val[ t1Idx.i() ] * t2_val[t2Idx.i()];
} else {
return ( t0Idx, t1Idx, t2Idx ) -> {
if (d == 0) return t2_val[t2Idx.i()];
else return t1_val[ t1Idx.i() ];
};
}
};
DefaultOperatorCreator<TertiaryNDAConsumer> convolutionCreator =
( inputs, d ) -> {
double[] t1_val = inputs[ 1 ].value64();
double[] t2_val = inputs[ 2 ].value64();
if ( d < 0 ) {
return ( t0Idx, t1Idx, t2Idx ) -> t1_val[inputs[ 1 ].indexOfIndices( t1Idx )] * t2_val[inputs[ 2 ].indexOfIndices(t2Idx)];
} else {
return ( t0Idx, t1Idx, t2Idx ) -> {
if (d == 0) return t2_val[inputs[ 2 ].indexOfIndices(t2Idx)];
else return t1_val[inputs[ 1 ].indexOfIndices( t1Idx )];
};
}
};
Convolution convolution = ConvUtil.getConv();//.createDeconvolutionFor( this.getOperator() );
setAlgorithm(
Convolution.class,
convolution
.setImplementationFor(
HostCPU.class,
HostImplementation
.withArity(3)
.andImplementation(
call ->
call.getDevice().getExecutor()
.threaded (
call.getTsrOfType( Number.class, 0 ).size(),
(Neureka.get().settings().indexing().isUsingArrayBasedIndexing())
? ( start, end ) ->
Convolution.convolve (
call.getTsrOfType( Number.class, 0 ), call.getTsrOfType( Number.class, 1 ), call.getTsrOfType( Number.class, 2 ),
call.getValOf( Arg.DerivIdx.class ), start, end,
convolutionCreator.create(
call.getTensors(),
-1//call.getValOf( Arg.DerivIdx.class )
)
)
: ( start, end ) ->
Convolution.convolve (
call.getTsrOfType( Number.class, 0 ), call.getTsrOfType( Number.class, 1 ), call.getTsrOfType( Number.class, 2 ),
call.getValOf( Arg.DerivIdx.class ), start, end,
convolutionNDICreator.create(
call.getTensors(),
-1//call.getValOf( Arg.DerivIdx.class )
)
)
)
)
)
.setImplementationFor(
OpenCLDevice.class,
CLImplementation.compiler()
.arity( 3 )
.kernelSource( convolution.getKernelSource() )
.activationSource( "value = src1 * src2;\n" )
.differentiationSource( "value += handle * drain;\n" )
.kernelPostfix( this.getFunction() )
.execution(
call -> {
int offset = ( call.getTsrOfType( Number.class, 0 ) != null ) ? 0 : 1;
int gwz = ( call.getTsrOfType( Number.class, 0 ) != null ) ? call.getTsrOfType( Number.class, 0 ).size() : call.getTsrOfType( Number.class, 1 ).size();
call.getDevice().getKernel(call)
.passAllOf( call.getTsrOfType( Number.class, offset ) )
.passAllOf( call.getTsrOfType( Number.class, offset + 1 ) )
.passAllOf( call.getTsrOfType( Number.class, offset + 2 ) )
.pass( call.getTsrOfType( Number.class, 0 ).rank() )
.pass( call.getValOf( Arg.DerivIdx.class ) ) //call.getValOf( Arg.DerivIdx.class )
.call( gwz );
}
)
.build()
)
);
}
@Override
public String stringify( String[] children ) {
StringBuilder reconstructed = new StringBuilder();
for ( int i = 0; i < children.length; ++i ) {
reconstructed.append( children[ i ] );
if ( i < children.length - 1 ) {
reconstructed.append(" x ");
}
}
return "(" + reconstructed + ")";
}
@Override
public String asDerivative( Function[] children, int derivationIndex) {
throw new IllegalStateException("Operation does not support dynamic derivation!");
}
@Override
public double calculate( double[] inputs, int j, int d, Function[] src ) {
return src[ 0 ].call( inputs, j );
}
}
| package neureka.backend.standard.operations.linear;
import neureka.IMPORT_0;
import neureka.backend.api.operations.AbstractOperation;
import neureka.backend.api.operations.OperationBuilder;
import neureka.backend.standard.algorithms.Convolution;
import neureka.backend.standard.implementations.CLImplementation;
import neureka.backend.standard.implementations.HostImplementation;
import neureka.backend.standard.operations.ConvUtil;
import neureka.calculus.Function;
import neureka.calculus.args.Arg;
import neureka.devices.host.HostCPU;
import neureka.devices.opencl.OpenCLDevice;
public class XConv extends AbstractOperation
{
public XConv()
{
super(
new OperationBuilder()
.setFunction( "mul_conv" )
.setOperator( "x" )
.setArity( 2 )
.setIsOperator( true )
.setIsIndexer( false )
.setIsDifferentiable( true )
.setIsInline( false )
);
DefaultOperatorCreator<TertiaryNDIConsumer> convolutionNDICreator =
( inputs, d ) -> {
double[] t1_val = inputs[ 1 ].value64();
double[] t2_val = inputs[ 2 ].value64();
if ( d < 0 ) {
return ( t0Idx, t1Idx, t2Idx ) -> t1_val[ t1Idx.i() ] * t2_val[t2Idx.i()];
} else {
return ( t0Idx, t1Idx, t2Idx ) -> {
if (d == 0) return t2_val[t2Idx.i()];
else return t1_val[ t1Idx.i() ];
};
}
};
DefaultOperatorCreator<TertiaryNDAConsumer> convolutionCreator =
( inputs, d ) -> {
double[] t1_val = inputs[ 1 ].value64();
double[] t2_val = inputs[ 2 ].value64();
if ( d < 0 ) {
return ( t0Idx, t1Idx, t2Idx ) -> t1_val[inputs[ 1 ].indexOfIndices( t1Idx )] * t2_val[inputs[ 2 ].indexOfIndices(t2Idx)];
} else {
return ( t0Idx, t1Idx, t2Idx ) -> {
if (d == 0) return t2_val[inputs[ 2 ].indexOfIndices(t2Idx)];
else return t1_val[inputs[ 1 ].indexOfIndices( t1Idx )];
};
}
};
Convolution VAR_0 = ConvUtil.getConv();//.createDeconvolutionFor( this.getOperator() );
setAlgorithm(
Convolution.class,
VAR_0
.setImplementationFor(
HostCPU.class,
HostImplementation
.withArity(3)
.andImplementation(
call ->
call.getDevice().getExecutor()
.threaded (
call.getTsrOfType( Number.class, 0 ).size(),
(IMPORT_0.get().settings().indexing().isUsingArrayBasedIndexing())
? ( start, end ) ->
Convolution.convolve (
call.getTsrOfType( Number.class, 0 ), call.getTsrOfType( Number.class, 1 ), call.getTsrOfType( Number.class, 2 ),
call.getValOf( Arg.DerivIdx.class ), start, end,
convolutionCreator.create(
call.getTensors(),
-1//call.getValOf( Arg.DerivIdx.class )
)
)
: ( start, end ) ->
Convolution.convolve (
call.getTsrOfType( Number.class, 0 ), call.getTsrOfType( Number.class, 1 ), call.getTsrOfType( Number.class, 2 ),
call.getValOf( Arg.DerivIdx.class ), start, end,
convolutionNDICreator.create(
call.getTensors(),
-1//call.getValOf( Arg.DerivIdx.class )
)
)
)
)
)
.setImplementationFor(
OpenCLDevice.class,
CLImplementation.compiler()
.arity( 3 )
.kernelSource( VAR_0.getKernelSource() )
.activationSource( "value = src1 * src2;\n" )
.differentiationSource( "value += handle * drain;\n" )
.kernelPostfix( this.getFunction() )
.execution(
call -> {
int offset = ( call.getTsrOfType( Number.class, 0 ) != null ) ? 0 : 1;
int gwz = ( call.getTsrOfType( Number.class, 0 ) != null ) ? call.getTsrOfType( Number.class, 0 ).size() : call.getTsrOfType( Number.class, 1 ).size();
call.getDevice().getKernel(call)
.passAllOf( call.getTsrOfType( Number.class, offset ) )
.passAllOf( call.getTsrOfType( Number.class, offset + 1 ) )
.passAllOf( call.getTsrOfType( Number.class, offset + 2 ) )
.pass( call.getTsrOfType( Number.class, 0 ).rank() )
.pass( call.getValOf( Arg.DerivIdx.class ) ) //call.getValOf( Arg.DerivIdx.class )
.call( gwz );
}
)
.build()
)
);
}
@Override
public String stringify( String[] children ) {
StringBuilder reconstructed = new StringBuilder();
for ( int i = 0; i < children.length; ++i ) {
reconstructed.append( children[ i ] );
if ( i < children.length - 1 ) {
reconstructed.append(" x ");
}
}
return "(" + reconstructed + ")";
}
@Override
public String asDerivative( Function[] children, int derivationIndex) {
throw new IllegalStateException("Operation does not support dynamic derivation!");
}
@Override
public double calculate( double[] inputs, int j, int d, Function[] src ) {
return src[ 0 ].call( inputs, j );
}
}
| 0.017205 | {'IMPORT_0': 'Neureka', 'VAR_0': 'convolution'} | java | OOP | 12.12% |
/**
* Wraps a ColumnFamilyRecordReader and converts CFRR's binary types to JanusGraph binary types.
*/
public class CassandraBinaryRecordReader extends RecordReader<StaticBuffer, Iterable<Entry>> {
private final ColumnFamilyRecordReader reader;
private KV currentKV;
private KV incompleteKV;
public CassandraBinaryRecordReader(final ColumnFamilyRecordReader reader) {
this.reader = reader;
}
@Override
public void initialize(final InputSplit inputSplit, final TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
reader.initialize(inputSplit, taskAttemptContext);
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
return null != (currentKV = completeNextKV());
}
private KV completeNextKV() throws IOException {
KV completedKV = null;
boolean hasNext;
do {
hasNext = reader.nextKeyValue();
if (!hasNext) {
completedKV = incompleteKV;
incompleteKV = null;
} else {
StaticArrayBuffer key = StaticArrayBuffer.of(reader.getCurrentKey());
SortedMap<ByteBuffer, ColumnFamilyRecordReader.Column> valueSortedMap = reader.getCurrentValue();
List<Entry> entries = new ArrayList<>(valueSortedMap.size());
for (Map.Entry<ByteBuffer, ColumnFamilyRecordReader.Column> ent : valueSortedMap.entrySet()) {
ByteBuffer col = ent.getKey();
ByteBuffer val = ent.getValue().value;
entries.add(StaticArrayEntry.of(StaticArrayBuffer.of(col), StaticArrayBuffer.of(val)));
}
if (null == incompleteKV) {
// Initialization; this should happen just once in an instance's lifetime
incompleteKV = new KV(key);
} else if (!incompleteKV.key.equals(key)) {
// The underlying Cassandra reader has just changed to a key we haven't seen yet
// This implies that there will be no more entries for the prior key
completedKV = incompleteKV;
incompleteKV = new KV(key);
}
incompleteKV.addEntries(entries);
}
/* Loop ends when either
* A) the cassandra reader ran out of data
* or
* B) the cassandra reader switched keys, thereby completing a KV */
} while (hasNext && null == completedKV);
return completedKV;
}
@Override
public StaticBuffer getCurrentKey() throws IOException, InterruptedException {
return currentKV.key;
}
@Override
public Iterable<Entry> getCurrentValue() throws IOException, InterruptedException {
return currentKV.entries;
}
@Override
public void close() throws IOException {
reader.close();
}
@Override
public float getProgress() {
return reader.getProgress();
}
private static class KV {
private final StaticArrayBuffer key;
private ArrayList<Entry> entries;
public KV(StaticArrayBuffer key) {
this.key = key;
}
public void addEntries(Collection<Entry> toAdd) {
if (null == entries)
entries = new ArrayList<>(toAdd.size());
entries.addAll(toAdd);
}
}
} | /**
* Wraps a ColumnFamilyRecordReader and converts CFRR's binary types to JanusGraph binary types.
*/
public class CLASS_0 extends CLASS_1<CLASS_2, CLASS_3<Entry>> {
private final ColumnFamilyRecordReader VAR_0;
private KV currentKV;
private KV incompleteKV;
public CLASS_0(final ColumnFamilyRecordReader VAR_0) {
this.VAR_0 = VAR_0;
}
@VAR_1
public void FUNC_0(final CLASS_4 inputSplit, final TaskAttemptContext taskAttemptContext) throws CLASS_5, InterruptedException {
VAR_0.FUNC_0(inputSplit, taskAttemptContext);
}
@VAR_1
public boolean nextKeyValue() throws CLASS_5, InterruptedException {
return null != (currentKV = completeNextKV());
}
private KV completeNextKV() throws CLASS_5 {
KV VAR_2 = null;
boolean VAR_3;
do {
VAR_3 = VAR_0.nextKeyValue();
if (!VAR_3) {
VAR_2 = incompleteKV;
incompleteKV = null;
} else {
CLASS_6 VAR_5 = VAR_4.of(VAR_0.FUNC_1());
CLASS_7<ByteBuffer, ColumnFamilyRecordReader.Column> valueSortedMap = VAR_0.FUNC_2();
CLASS_8<Entry> VAR_6 = new CLASS_9<>(valueSortedMap.size());
for (CLASS_10.Entry<ByteBuffer, ColumnFamilyRecordReader.Column> ent : valueSortedMap.FUNC_3()) {
ByteBuffer VAR_7 = ent.FUNC_4();
ByteBuffer VAR_8 = ent.getValue().value;
VAR_6.add(StaticArrayEntry.of(VAR_4.of(VAR_7), VAR_4.of(VAR_8)));
}
if (null == incompleteKV) {
// Initialization; this should happen just once in an instance's lifetime
incompleteKV = new KV(VAR_5);
} else if (!incompleteKV.VAR_5.FUNC_5(VAR_5)) {
// The underlying Cassandra reader has just changed to a key we haven't seen yet
// This implies that there will be no more entries for the prior key
VAR_2 = incompleteKV;
incompleteKV = new KV(VAR_5);
}
incompleteKV.FUNC_6(VAR_6);
}
/* Loop ends when either
* A) the cassandra reader ran out of data
* or
* B) the cassandra reader switched keys, thereby completing a KV */
} while (VAR_3 && null == VAR_2);
return VAR_2;
}
@VAR_1
public CLASS_2 FUNC_1() throws CLASS_5, InterruptedException {
return currentKV.VAR_5;
}
@VAR_1
public CLASS_3<Entry> FUNC_2() throws CLASS_5, InterruptedException {
return currentKV.VAR_6;
}
@VAR_1
public void FUNC_7() throws CLASS_5 {
VAR_0.FUNC_7();
}
@VAR_1
public float FUNC_8() {
return VAR_0.FUNC_8();
}
private static class KV {
private final CLASS_6 VAR_5;
private CLASS_9<Entry> VAR_6;
public KV(CLASS_6 VAR_5) {
this.VAR_5 = VAR_5;
}
public void FUNC_6(CLASS_11<Entry> VAR_9) {
if (null == VAR_6)
VAR_6 = new CLASS_9<>(VAR_9.size());
VAR_6.addAll(VAR_9);
}
}
} | 0.572552 | {'CLASS_0': 'CassandraBinaryRecordReader', 'CLASS_1': 'RecordReader', 'CLASS_2': 'StaticBuffer', 'CLASS_3': 'Iterable', 'VAR_0': 'reader', 'VAR_1': 'Override', 'FUNC_0': 'initialize', 'CLASS_4': 'InputSplit', 'CLASS_5': 'IOException', 'VAR_2': 'completedKV', 'VAR_3': 'hasNext', 'CLASS_6': 'StaticArrayBuffer', 'VAR_4': 'StaticArrayBuffer', 'VAR_5': 'key', 'FUNC_1': 'getCurrentKey', 'CLASS_7': 'SortedMap', 'FUNC_2': 'getCurrentValue', 'CLASS_8': 'List', 'VAR_6': 'entries', 'CLASS_9': 'ArrayList', 'CLASS_10': 'Map', 'FUNC_3': 'entrySet', 'VAR_7': 'col', 'FUNC_4': 'getKey', 'VAR_8': 'val', 'FUNC_5': 'equals', 'FUNC_6': 'addEntries', 'FUNC_7': 'close', 'FUNC_8': 'getProgress', 'CLASS_11': 'Collection', 'VAR_9': 'toAdd'} | java | OOP | 19.86% |
/*
* 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.zto.zms.dal.model;
import java.util.Date;
public class ServiceProcess {
private Integer id;
private Integer serviceId;
private Integer instanceId;
/**
* 运行状态
*/
private String runningStatus;
/**
* 初始化配置文件状态
*/
private String status;
private String creator;
private String modifier;
private Date gmtCreate;
private Date gmtModified;
public String getRunningStatus() {
return runningStatus;
}
public void setRunningStatus(String runningStatus) {
this.runningStatus = runningStatus;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getServiceId() {
return serviceId;
}
public void setServiceId(Integer serviceId) {
this.serviceId = serviceId;
}
public Integer getInstanceId() {
return instanceId;
}
public void setInstanceId(Integer instanceId) {
this.instanceId = instanceId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getModifier() {
return modifier;
}
public void setModifier(String modifier) {
this.modifier = modifier;
}
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
}
| /*
* 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 IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4;
import IMPORT_5.IMPORT_6.Date;
public class CLASS_0 {
private Integer VAR_0;
private Integer serviceId;
private Integer instanceId;
/**
* 运行状态
*/
private CLASS_1 VAR_1;
/**
* 初始化配置文件状态
*/
private CLASS_1 status;
private CLASS_1 VAR_2;
private CLASS_1 VAR_3;
private Date VAR_4;
private Date VAR_5;
public CLASS_1 getRunningStatus() {
return VAR_1;
}
public void FUNC_0(CLASS_1 VAR_1) {
this.VAR_1 = VAR_1;
}
public Integer FUNC_1() {
return VAR_0;
}
public void FUNC_2(Integer VAR_0) {
this.VAR_0 = VAR_0;
}
public Integer FUNC_3() {
return serviceId;
}
public void setServiceId(Integer serviceId) {
this.serviceId = serviceId;
}
public Integer getInstanceId() {
return instanceId;
}
public void setInstanceId(Integer instanceId) {
this.instanceId = instanceId;
}
public CLASS_1 FUNC_4() {
return status;
}
public void FUNC_5(CLASS_1 status) {
this.status = status;
}
public CLASS_1 getCreator() {
return VAR_2;
}
public void FUNC_6(CLASS_1 VAR_2) {
this.VAR_2 = VAR_2;
}
public CLASS_1 FUNC_7() {
return VAR_3;
}
public void FUNC_8(CLASS_1 VAR_3) {
this.VAR_3 = VAR_3;
}
public Date getGmtCreate() {
return VAR_4;
}
public void FUNC_9(Date VAR_4) {
this.VAR_4 = VAR_4;
}
public Date FUNC_10() {
return VAR_5;
}
public void FUNC_11(Date VAR_5) {
this.VAR_5 = VAR_5;
}
}
| 0.808957 | {'IMPORT_0': 'com', 'IMPORT_1': 'zto', 'IMPORT_2': 'zms', 'IMPORT_3': 'dal', 'IMPORT_4': 'model', 'IMPORT_5': 'java', 'IMPORT_6': 'util', 'CLASS_0': 'ServiceProcess', 'VAR_0': 'id', 'CLASS_1': 'String', 'VAR_1': 'runningStatus', 'VAR_2': 'creator', 'VAR_3': 'modifier', 'VAR_4': 'gmtCreate', 'VAR_5': 'gmtModified', 'FUNC_0': 'setRunningStatus', 'FUNC_1': 'getId', 'FUNC_2': 'setId', 'FUNC_3': 'getServiceId', 'FUNC_4': 'getStatus', 'FUNC_5': 'setStatus', 'FUNC_6': 'setCreator', 'FUNC_7': 'getModifier', 'FUNC_8': 'setModifier', 'FUNC_9': 'setGmtCreate', 'FUNC_10': 'getGmtModified', 'FUNC_11': 'setGmtModified'} | java | Hibrido | 100.00% |
package org.lndroid.framework.client;
import java.lang.reflect.Type;
public interface IPluginTransaction {
// id of plugin that is communicated with using this tx
String pluginId();
// returns the tx id
String id();
// true if tx is started and still active (no error was returned by server)
boolean isActive();
// to override the client's current token
void setSessionToken(String token);
// call to start request
void start(Object r, Type type);
// pass tx timeout in ms
void start(Object r, Type type, long timeout);
// call if it's an input stream to provide more inputs
void send(Object r, Type type);
// call to stop subscription or request streaming, etc
void stop();
// release tx resources, optional, but
// might allow client to release some memory
void destroy();
// if owner does not want to store a reference to the tx,
// and instead want's it to exist until done,
// call detach: client will hold a strong reference to this tx,
// and it will self-destruct when done
void detach();
}
| package org.IMPORT_0.framework.client;
import IMPORT_1.lang.IMPORT_2.IMPORT_3;
public interface IPluginTransaction {
// id of plugin that is communicated with using this tx
String FUNC_0();
// returns the tx id
String id();
// true if tx is started and still active (no error was returned by server)
boolean FUNC_1();
// to override the client's current token
void FUNC_2(String VAR_0);
// call to start request
void start(CLASS_0 r, IMPORT_3 VAR_1);
// pass tx timeout in ms
void start(CLASS_0 r, IMPORT_3 VAR_1, long VAR_2);
// call if it's an input stream to provide more inputs
void send(CLASS_0 r, IMPORT_3 VAR_1);
// call to stop subscription or request streaming, etc
void FUNC_3();
// release tx resources, optional, but
// might allow client to release some memory
void destroy();
// if owner does not want to store a reference to the tx,
// and instead want's it to exist until done,
// call detach: client will hold a strong reference to this tx,
// and it will self-destruct when done
void detach();
}
| 0.408857 | {'IMPORT_0': 'lndroid', 'IMPORT_1': 'java', 'IMPORT_2': 'reflect', 'IMPORT_3': 'Type', 'FUNC_0': 'pluginId', 'FUNC_1': 'isActive', 'FUNC_2': 'setSessionToken', 'VAR_0': 'token', 'CLASS_0': 'Object', 'VAR_1': 'type', 'VAR_2': 'timeout', 'FUNC_3': 'stop'} | java | Texto | 7.49% |
package database.connectors;
import command.util.highscores.BangPlayer;
import database.Connector;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
public final class BangConnector extends Connector {
/**
* @see Connector
* Initializes the table as "bang".
*/
public BangConnector() {
super("bang");
}
/**
* Searches the bang table for a row with a matching user ID and returns
* whether or not such a row was found.
*
* @param userId the id number of the Discord user being searched for
* @return true if found, false if not found or error occurs
*/
private boolean userExists(long userId) {
return super.userExists(userId, getTable());
}
/**
* Checks if the user is eligible for their daily reward.
*
* @param userId the Discord user's ID number
* @return true if the user if eligible, false if not
* @throws SQLException may be thrown when accessing the long "last_daily" from a ResultSet
*/
public boolean isEligibleForDaily(long userId) throws SQLException {
if (!userExists(userId)) addUser(userId);
return new Date().getTime() - getUserRow(userId, getTable())
.getLong("last_daily") >= 86400000;
}
/**
* Sets the new last daily reward time for a specified user.
*
* @param userId the user's ID number
* @param lastPlayedTime the time in ms since epoch that is the new user's daily
* @throws SQLException may be thrown when making a prepared statement
*/
public void setDaily(long userId, long lastPlayedTime) throws SQLException {
if (!userExists(userId)) addUser(userId);
getConnection().prepareStatement("UPDATE bang SET last_daily = " + lastPlayedTime
+ " WHERE user = " + userId).executeUpdate();
}
/**
* Returns a user's row in the table.
*
* @param userId the user's ID number
* @return a ResultSet containing the user's entire row in bang
*/
public ResultSet getUserRow(long userId) {
if (!userExists(userId)) addUser(userId);
return getUserRow(userId, getTable());
}
/**
* Returns the time at which a user last received a daily reward.
*
* @param userId the user's ID number
* @return the long int that is the time at which the last daily reward was received
* @throws SQLException may be thrown when making a prepared statement
*/
public long getDaily(long userId) throws SQLException {
if (!userExists(userId)) addUser(userId);
ResultSet rs = getConnection()
.prepareStatement("SELECT last_daily FROM bang WHERE user=" + userId)
.executeQuery();
rs.next();
return rs.getLong("last_daily") + 86460000;
}
/**
* Gets a list of the Bang players with the most attempts in order of
* greatest to least.
*
* @return list of top 10 bang attempts players
* @throws SQLException may be thrown when interacting with database
*/
public ArrayList<BangPlayer> getMostAttemptsPlayers() throws SQLException {
ResultSet resultSet = getConnection().prepareStatement("SELECT * FROM bang "
+ "WHERE " + new Date().getTime() + " - last_played < 604800000 "
+ "GROUP BY user, tries "
+ "ORDER BY tries").executeQuery();
ArrayList<BangPlayer> players = new ArrayList<>();
if (resultSet.last()) {
do {
players.add(new BangPlayer(resultSet.getLong("user"),
resultSet.getInt("tries"), resultSet.getInt("deaths"),
resultSet.getInt("jams")));
} while (resultSet.previous());
}
return players;
}
/**
* Gets a list of the Bang players with the highest survival rates
* in order of greatest to least.
*
* @return list of top 10 bang survival rate players
* @throws SQLException may be thrown when interacting with database
*/
public ArrayList<BangPlayer> getLuckiestPlayers() throws SQLException {
ResultSet resultSet = getConnection().prepareStatement("SELECT * FROM bang "
+ "WHERE " + new Date().getTime() + " - last_played < 604800000 "
+ "AND tries >= 20 "
+ "GROUP BY user, tries "
+ "ORDER BY death_rate").executeQuery();
ArrayList<BangPlayer> players = new ArrayList<>();
if (resultSet.first()) {
do {
players.add(new BangPlayer(resultSet.getLong("user"),
resultSet.getInt("tries"), resultSet.getInt("deaths"),
resultSet.getInt("jams")));
} while (resultSet.next());
}
return players;
}
/**
* Returns the total number of times people played Bang.
*
* @return number of bang attempts
* @throws SQLException may be thrown when interacting with database
*/
public int getTotalAttempts() throws SQLException {
int attempts = 0;
ResultSet rs = getConnection().prepareStatement("SELECT * FROM bang").executeQuery();
while (rs.next())
attempts += rs.getInt("tries");
return attempts;
}
/**
* Returns the total number of times people died in Bang.
*
* @return number of bang deaths
* @throws SQLException may be thrown when interacting with database
*/
public int getTotalDeaths() throws SQLException {
int deaths = 0;
ResultSet rs = getConnection().prepareStatement("SELECT * FROM bang").executeQuery();
while (rs.next())
deaths += rs.getInt("deaths");
return deaths;
}
/**
* Resets the streak to 0 for all players who have a last_played that is more than
* 24 hours since the current time.
*
* @throws SQLException may be thrown when interacting with database
*/
public void pruneStreaks() throws SQLException {
getConnection().prepareStatement("UPDATE bang SET streak = 0 WHERE "
+ new Date().getTime() + " - last_played > 86460000").executeUpdate();
}
/**
* Adds a new user to the bang table based on their ID.
*
* @param userId the ID number of the new user being added
*/
@Override
public void addUser(long userId) {
try {
getConnection().prepareStatement("INSERT INTO bang "
+ "(user, tries, deaths, jams, last_played, streak) "
+ "VALUES (" + userId + ", 0, 0, 0, 0, 0)").executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| package IMPORT_0.connectors;
import IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4;
import IMPORT_0.IMPORT_5;
import IMPORT_6.IMPORT_7.ResultSet;
import IMPORT_6.IMPORT_7.SQLException;
import IMPORT_6.IMPORT_2.IMPORT_8;
import IMPORT_6.IMPORT_2.IMPORT_9;
public final class CLASS_0 extends IMPORT_5 {
/**
* @see Connector
* Initializes the table as "bang".
*/
public CLASS_0() {
super("bang");
}
/**
* Searches the bang table for a row with a matching user ID and returns
* whether or not such a row was found.
*
* @param userId the id number of the Discord user being searched for
* @return true if found, false if not found or error occurs
*/
private boolean FUNC_0(long VAR_0) {
return super.FUNC_0(VAR_0, getTable());
}
/**
* Checks if the user is eligible for their daily reward.
*
* @param userId the Discord user's ID number
* @return true if the user if eligible, false if not
* @throws SQLException may be thrown when accessing the long "last_daily" from a ResultSet
*/
public boolean FUNC_1(long VAR_0) throws SQLException {
if (!FUNC_0(VAR_0)) FUNC_2(VAR_0);
return new IMPORT_9().FUNC_3() - getUserRow(VAR_0, getTable())
.FUNC_4("last_daily") >= 86400000;
}
/**
* Sets the new last daily reward time for a specified user.
*
* @param userId the user's ID number
* @param lastPlayedTime the time in ms since epoch that is the new user's daily
* @throws SQLException may be thrown when making a prepared statement
*/
public void FUNC_5(long VAR_0, long VAR_1) throws SQLException {
if (!FUNC_0(VAR_0)) FUNC_2(VAR_0);
FUNC_6().FUNC_7("UPDATE bang SET last_daily = " + VAR_1
+ " WHERE user = " + VAR_0).FUNC_8();
}
/**
* Returns a user's row in the table.
*
* @param userId the user's ID number
* @return a ResultSet containing the user's entire row in bang
*/
public ResultSet getUserRow(long VAR_0) {
if (!FUNC_0(VAR_0)) FUNC_2(VAR_0);
return getUserRow(VAR_0, getTable());
}
/**
* Returns the time at which a user last received a daily reward.
*
* @param userId the user's ID number
* @return the long int that is the time at which the last daily reward was received
* @throws SQLException may be thrown when making a prepared statement
*/
public long getDaily(long VAR_0) throws SQLException {
if (!FUNC_0(VAR_0)) FUNC_2(VAR_0);
ResultSet VAR_2 = FUNC_6()
.FUNC_7("SELECT last_daily FROM bang WHERE user=" + VAR_0)
.executeQuery();
VAR_2.FUNC_9();
return VAR_2.FUNC_4("last_daily") + 86460000;
}
/**
* Gets a list of the Bang players with the most attempts in order of
* greatest to least.
*
* @return list of top 10 bang attempts players
* @throws SQLException may be thrown when interacting with database
*/
public IMPORT_8<IMPORT_4> FUNC_10() throws SQLException {
ResultSet VAR_3 = FUNC_6().FUNC_7("SELECT * FROM bang "
+ "WHERE " + new IMPORT_9().FUNC_3() + " - last_played < 604800000 "
+ "GROUP BY user, tries "
+ "ORDER BY tries").executeQuery();
IMPORT_8<IMPORT_4> players = new IMPORT_8<>();
if (VAR_3.FUNC_11()) {
do {
players.add(new IMPORT_4(VAR_3.FUNC_4("user"),
VAR_3.FUNC_12("tries"), VAR_3.FUNC_12("deaths"),
VAR_3.FUNC_12("jams")));
} while (VAR_3.previous());
}
return players;
}
/**
* Gets a list of the Bang players with the highest survival rates
* in order of greatest to least.
*
* @return list of top 10 bang survival rate players
* @throws SQLException may be thrown when interacting with database
*/
public IMPORT_8<IMPORT_4> getLuckiestPlayers() throws SQLException {
ResultSet VAR_3 = FUNC_6().FUNC_7("SELECT * FROM bang "
+ "WHERE " + new IMPORT_9().FUNC_3() + " - last_played < 604800000 "
+ "AND tries >= 20 "
+ "GROUP BY user, tries "
+ "ORDER BY death_rate").executeQuery();
IMPORT_8<IMPORT_4> players = new IMPORT_8<>();
if (VAR_3.FUNC_13()) {
do {
players.add(new IMPORT_4(VAR_3.FUNC_4("user"),
VAR_3.FUNC_12("tries"), VAR_3.FUNC_12("deaths"),
VAR_3.FUNC_12("jams")));
} while (VAR_3.FUNC_9());
}
return players;
}
/**
* Returns the total number of times people played Bang.
*
* @return number of bang attempts
* @throws SQLException may be thrown when interacting with database
*/
public int getTotalAttempts() throws SQLException {
int VAR_4 = 0;
ResultSet VAR_2 = FUNC_6().FUNC_7("SELECT * FROM bang").executeQuery();
while (VAR_2.FUNC_9())
VAR_4 += VAR_2.FUNC_12("tries");
return VAR_4;
}
/**
* Returns the total number of times people died in Bang.
*
* @return number of bang deaths
* @throws SQLException may be thrown when interacting with database
*/
public int FUNC_14() throws SQLException {
int VAR_5 = 0;
ResultSet VAR_2 = FUNC_6().FUNC_7("SELECT * FROM bang").executeQuery();
while (VAR_2.FUNC_9())
VAR_5 += VAR_2.FUNC_12("deaths");
return VAR_5;
}
/**
* Resets the streak to 0 for all players who have a last_played that is more than
* 24 hours since the current time.
*
* @throws SQLException may be thrown when interacting with database
*/
public void pruneStreaks() throws SQLException {
FUNC_6().FUNC_7("UPDATE bang SET streak = 0 WHERE "
+ new IMPORT_9().FUNC_3() + " - last_played > 86460000").FUNC_8();
}
/**
* Adds a new user to the bang table based on their ID.
*
* @param userId the ID number of the new user being added
*/
@VAR_6
public void FUNC_2(long VAR_0) {
try {
FUNC_6().FUNC_7("INSERT INTO bang "
+ "(user, tries, deaths, jams, last_played, streak) "
+ "VALUES (" + VAR_0 + ", 0, 0, 0, 0, 0)").FUNC_8();
} catch (CLASS_1 VAR_7) {
VAR_7.FUNC_15();
}
}
}
| 0.765899 | {'IMPORT_0': 'database', 'IMPORT_1': 'command', 'IMPORT_2': 'util', 'IMPORT_3': 'highscores', 'IMPORT_4': 'BangPlayer', 'IMPORT_5': 'Connector', 'IMPORT_6': 'java', 'IMPORT_7': 'sql', 'IMPORT_8': 'ArrayList', 'IMPORT_9': 'Date', 'CLASS_0': 'BangConnector', 'FUNC_0': 'userExists', 'VAR_0': 'userId', 'FUNC_1': 'isEligibleForDaily', 'FUNC_2': 'addUser', 'FUNC_3': 'getTime', 'FUNC_4': 'getLong', 'FUNC_5': 'setDaily', 'VAR_1': 'lastPlayedTime', 'FUNC_6': 'getConnection', 'FUNC_7': 'prepareStatement', 'FUNC_8': 'executeUpdate', 'VAR_2': 'rs', 'FUNC_9': 'next', 'FUNC_10': 'getMostAttemptsPlayers', 'VAR_3': 'resultSet', 'FUNC_11': 'last', 'FUNC_12': 'getInt', 'FUNC_13': 'first', 'VAR_4': 'attempts', 'FUNC_14': 'getTotalDeaths', 'VAR_5': 'deaths', 'VAR_6': 'Override', 'CLASS_1': 'Exception', 'VAR_7': 'e', 'FUNC_15': 'printStackTrace'} | java | OOP | 12.51% |
package test612;
@interface Annot {
String value() default "";
}
@interface Annot2 {
}
public class A {
A() {
}
}
class B {
}
| package test612;
@interface Annot {
String value() default "";
}
@interface Annot2 {
}
public class A {
A() {
}
}
class B {
}
| 0.169598 | {} | java | Texto | 17.24% |
package com.habr;
import java.sql.*;
public class ConnectH2 {
public static void main(String[] args) {
try {
Class.forName("org.h2.Driver").newInstance();
// Connection conn = DriverManager.getConnection("jdbc:h2:test", "sa", "");
// String url = "\"jdbc:h2:~/test\"";
String url = "jdbc:h2:mem:";
// String url = "jdbc:h2:mem;" + "INIT=RUNSCRIPT FROM '~resources/create.sql'\\;";
// http://www.h2database.com/html/features.html#execute_sql_on_connection
// EmbeddedDatabase db = new EmbeddedDatabaseBuilder()
// .setType(EmbeddedDatabaseType.H2)
// .setName("testDb;DB_CLOSE_ON_EXIT=FALSE;MODE=Oracle;INIT=create " +
// "schema if not exists " +
// "schema_a\\;create schema if not exists schema_b;" +
// "DB_CLOSE_DELAY=-1;")
// .addScript("sql/provPlan/createTable.sql")
// .addScript("sql/provPlan/insertData.sql")
// .addScript("sql/provPlan/insertSpecRel.sql")
// .build();
Connection conn = DriverManager.getConnection(url, "sa", "");
Statement st = null;
st = conn.createStatement();
// st.execute("CREATE TABLE IF NOT EXISTS TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
// st.execute("CREATE TABLE TEST ( \n" +
// " id INT NOT NULL, \n" +
// " name VARCHAR(50) NOT NULL, \n" +
// " default VARCHAR(20) NOT NULL, \n" +
// " submission_date DATE \n" +
// ");");
// st.execute("CREATE TABLE TEST ( \n" +
// " ID INT PRIMARY KEY, \n" +
// " name VARCHAR(50) NOT NULL \n" +
// ");");
// http://www.mastertheboss.com/jboss-server/jboss-datasource/h2-database-cheatsheet
// Значение NULL не разрешено для поля "ID"
// st.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
st.execute("create table TEST(id integer, name varchar(10))");
st.execute("INSERT INTO TEST VALUES(default,'HELLO')");
st.execute("INSERT INTO TEST(NAME) VALUES('JOHN')");
String name1 = "Jack";
String q = "insert into TEST(name) values(?)";
PreparedStatement st1 = null;
st1 = conn.prepareStatement(q);
st1.setString(1, name1);
st1.execute();
ResultSet result;
result = st.executeQuery("SELECT * FROM TEST");
while (result.next()) {
String name = result.getString("NAME");
System.out.println(result.getString("ID") + " " + name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | package IMPORT_0.IMPORT_1;
import IMPORT_2.IMPORT_3.*;
public class CLASS_0 {
public static void FUNC_0(CLASS_1[] VAR_0) {
try {
VAR_1.FUNC_1("org.h2.Driver").FUNC_2();
// Connection conn = DriverManager.getConnection("jdbc:h2:test", "sa", "");
// String url = "\"jdbc:h2:~/test\"";
CLASS_1 VAR_2 = "jdbc:h2:mem:";
// String url = "jdbc:h2:mem;" + "INIT=RUNSCRIPT FROM '~resources/create.sql'\\;";
// http://www.h2database.com/html/features.html#execute_sql_on_connection
// EmbeddedDatabase db = new EmbeddedDatabaseBuilder()
// .setType(EmbeddedDatabaseType.H2)
// .setName("testDb;DB_CLOSE_ON_EXIT=FALSE;MODE=Oracle;INIT=create " +
// "schema if not exists " +
// "schema_a\\;create schema if not exists schema_b;" +
// "DB_CLOSE_DELAY=-1;")
// .addScript("sql/provPlan/createTable.sql")
// .addScript("sql/provPlan/insertData.sql")
// .addScript("sql/provPlan/insertSpecRel.sql")
// .build();
CLASS_2 VAR_3 = VAR_4.FUNC_3(VAR_2, "sa", "");
CLASS_3 VAR_5 = null;
VAR_5 = VAR_3.FUNC_4();
// st.execute("CREATE TABLE IF NOT EXISTS TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
// st.execute("CREATE TABLE TEST ( \n" +
// " id INT NOT NULL, \n" +
// " name VARCHAR(50) NOT NULL, \n" +
// " default VARCHAR(20) NOT NULL, \n" +
// " submission_date DATE \n" +
// ");");
// st.execute("CREATE TABLE TEST ( \n" +
// " ID INT PRIMARY KEY, \n" +
// " name VARCHAR(50) NOT NULL \n" +
// ");");
// http://www.mastertheboss.com/jboss-server/jboss-datasource/h2-database-cheatsheet
// Значение NULL не разрешено для поля "ID"
// st.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
VAR_5.FUNC_5("create table TEST(id integer, name varchar(10))");
VAR_5.FUNC_5("INSERT INTO TEST VALUES(default,'HELLO')");
VAR_5.FUNC_5("INSERT INTO TEST(NAME) VALUES('JOHN')");
CLASS_1 VAR_6 = "Jack";
CLASS_1 VAR_7 = "insert into TEST(name) values(?)";
CLASS_4 VAR_8 = null;
VAR_8 = VAR_3.FUNC_6(VAR_7);
VAR_8.FUNC_7(1, VAR_6);
VAR_8.FUNC_5();
CLASS_5 VAR_9;
VAR_9 = VAR_5.FUNC_8("SELECT * FROM TEST");
while (VAR_9.FUNC_9()) {
CLASS_1 VAR_10 = VAR_9.FUNC_10("NAME");
VAR_11.VAR_12.FUNC_11(VAR_9.FUNC_10("ID") + " " + VAR_10);
}
} catch (CLASS_6 VAR_13) {
VAR_13.FUNC_12();
}
}
} | 0.96719 | {'IMPORT_0': 'com', 'IMPORT_1': 'habr', 'IMPORT_2': 'java', 'IMPORT_3': 'sql', 'CLASS_0': 'ConnectH2', 'FUNC_0': 'main', 'CLASS_1': 'String', 'VAR_0': 'args', 'VAR_1': 'Class', 'FUNC_1': 'forName', 'FUNC_2': 'newInstance', 'VAR_2': 'url', 'CLASS_2': 'Connection', 'VAR_3': 'conn', 'VAR_4': 'DriverManager', 'FUNC_3': 'getConnection', 'CLASS_3': 'Statement', 'VAR_5': 'st', 'FUNC_4': 'createStatement', 'FUNC_5': 'execute', 'VAR_6': 'name1', 'VAR_7': 'q', 'CLASS_4': 'PreparedStatement', 'VAR_8': 'st1', 'FUNC_6': 'prepareStatement', 'FUNC_7': 'setString', 'CLASS_5': 'ResultSet', 'VAR_9': 'result', 'FUNC_8': 'executeQuery', 'FUNC_9': 'next', 'VAR_10': 'name', 'FUNC_10': 'getString', 'VAR_11': 'System', 'VAR_12': 'out', 'FUNC_11': 'println', 'CLASS_6': 'Exception', 'VAR_13': 'e', 'FUNC_12': 'printStackTrace'} | java | OOP | 83.00% |
/*
* Must call this for the 'execute' function to work.
*/
public static void init() {
Graph txGraph = StartupSoft.factory.getTx();
try {
ActionScheduler.rpiUrl = txGraph.getFirstVertexOfClass(DBCN.V.extInterface.hw.controller.rpi.cn).getProperty(LP.data);
}
catch (Exception e) {
e.printStackTrace();
noRpi = true;
}
txGraph.shutdown();
externalIOConfig = new ExternalIOConfig();
try {
YamlReader hardwareConfigReader = new YamlReader(new FileReader("config/externalIOConfig.yml"));
externalIOConfig = hardwareConfigReader.read(ExternalIOConfig.class);
} catch (YamlException | FileNotFoundException e) {
throw new IllegalStateException(e);
}
} | /*
* Must call this for the 'execute' function to work.
*/
public static void init() {
Graph txGraph = StartupSoft.factory.getTx();
try {
ActionScheduler.VAR_0 = txGraph.getFirstVertexOfClass(DBCN.V.VAR_1.VAR_2.controller.rpi.cn).getProperty(LP.data);
}
catch (Exception e) {
e.printStackTrace();
noRpi = true;
}
txGraph.shutdown();
externalIOConfig = new ExternalIOConfig();
try {
YamlReader hardwareConfigReader = new YamlReader(new FileReader("config/externalIOConfig.yml"));
externalIOConfig = hardwareConfigReader.read(ExternalIOConfig.class);
} catch (YamlException | FileNotFoundException e) {
throw new IllegalStateException(e);
}
} | 0.048666 | {'VAR_0': 'rpiUrl', 'VAR_1': 'extInterface', 'VAR_2': 'hw'} | java | Procedural | 75.25% |
package muyu.system.service;
import muyu.system.common.service.CrudService;
import muyu.system.dao.DictDao;
import muyu.system.entity.Dict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 千山鸟飞绝,万径人踪灭。
* 孤舟蓑笠翁,独钓寒江雪。
*
* @author: 于其先
* @date: 2017/9/15
* @version: 1.0.0
*/
@Service
@Transactional
public class DictService extends CrudService<DictDao,Dict>{
}
| package muyu.system.IMPORT_0;
import muyu.system.common.IMPORT_0.CrudService;
import muyu.system.dao.DictDao;
import muyu.system.entity.Dict;
import org.springframework.IMPORT_1.Service;
import org.springframework.IMPORT_2.annotation.IMPORT_3;
/**
* 千山鸟飞绝,万径人踪灭。
* 孤舟蓑笠翁,独钓寒江雪。
*
* @author: 于其先
* @date: 2017/9/15
* @version: 1.0.0
*/
@Service
@IMPORT_3
public class CLASS_0 extends CrudService<DictDao,Dict>{
}
| 0.244163 | {'IMPORT_0': 'service', 'IMPORT_1': 'stereotype', 'IMPORT_2': 'transaction', 'IMPORT_3': 'Transactional', 'CLASS_0': 'DictService'} | java | OOP | 100.00% |
/**
* A Jackson implementation for {@link Log}. This class extends the {@link JacksonEvent}.
*/
public class JacksonLog extends JacksonEvent implements Log {
protected JacksonLog(final Builder builder) {
super(builder);
checkArgument(this.getMetadata().getEventType().equals("LOG"), "eventType must be of type Log");
}
/**
* Constructs an empty builder.
* @return a builder
* @since 1.2
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for creating {@link JacksonLog}.
* @since 1.2
*/
public static class Builder extends JacksonEvent.Builder<Builder> {
@Override
public Builder getThis() {
return this;
}
/**
* Returns a newly created {@link JacksonLog}.
* @return a log
* @since 1.2
*/
public JacksonLog build() {
this.withEventType(EventType.LOG.toString());
return new JacksonLog(this);
}
}
} | /**
* A Jackson implementation for {@link Log}. This class extends the {@link JacksonEvent}.
*/
public class JacksonLog extends JacksonEvent implements Log {
protected JacksonLog(final Builder builder) {
super(builder);
checkArgument(this.getMetadata().getEventType().equals("LOG"), "eventType must be of type Log");
}
/**
* Constructs an empty builder.
* @return a builder
* @since 1.2
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for creating {@link JacksonLog}.
* @since 1.2
*/
public static class Builder extends JacksonEvent.Builder<Builder> {
@Override
public Builder getThis() {
return this;
}
/**
* Returns a newly created {@link JacksonLog}.
* @return a log
* @since 1.2
*/
public JacksonLog build() {
this.withEventType(EventType.LOG.toString());
return new JacksonLog(this);
}
}
} | 0.088148 | {} | java | Texto | 3.73% |
package Factory.SimpleFactory;
public class Consumer {
public static void main(String[] args) {
String message;
LipStick ls = Store.getLipStick("Dior");
if (ls == null) {
System.out.println("no this lipstick...");
} else {
ls.show();
}
}
}
| package IMPORT_0.SimpleFactory;
public class CLASS_0 {
public static void FUNC_0(CLASS_1[] VAR_0) {
CLASS_1 message;
LipStick ls = VAR_1.FUNC_1("Dior");
if (ls == null) {
System.VAR_2.println("no this lipstick...");
} else {
ls.show();
}
}
}
| 0.571211 | {'IMPORT_0': 'Factory', 'CLASS_0': 'Consumer', 'FUNC_0': 'main', 'CLASS_1': 'String', 'VAR_0': 'args', 'VAR_1': 'Store', 'FUNC_1': 'getLipStick', 'VAR_2': 'out'} | java | OOP | 100.00% |
package za.co.twyst.tweetnacl.test;
import java.util.Arrays;
import java.util.Random;
import za.co.twyst.tweetnacl.TweetNaCl;
public class TestCryptoOneTimeAuth extends TweetNaClTest {
// CONSTANTS
// UNIT TESTS
/**
* crypto_hash (adapted from tests/onetimeauth.c)
*
*/
public void testCryptoOneTimeAuth() throws Exception {
final byte[] message = { (byte) 0x8e, (byte) 0x99, (byte) 0x3b, (byte) 0x9f,
(byte) 0x48, (byte) 0x68, (byte) 0x12, (byte) 0x73,
(byte) 0xc2, (byte) 0x96, (byte) 0x50, (byte) 0xba,
(byte) 0x32, (byte) 0xfc, (byte) 0x76, (byte) 0xce,
(byte) 0x48, (byte) 0x33, (byte) 0x2e, (byte) 0xa7,
(byte) 0x16, (byte) 0x4d, (byte) 0x96, (byte) 0xa4,
(byte) 0x47, (byte) 0x6f, (byte) 0xb8, (byte) 0xc5,
(byte) 0x31, (byte) 0xa1, (byte) 0x18, (byte) 0x6a,
(byte) 0xc0, (byte) 0xdf, (byte) 0xc1, (byte) 0x7c,
(byte) 0x98, (byte) 0xdc, (byte) 0xe8, (byte) 0x7b,
(byte) 0x4d, (byte) 0xa7, (byte) 0xf0, (byte) 0x11,
(byte) 0xec, (byte) 0x48, (byte) 0xc9, (byte) 0x72,
(byte) 0x71, (byte) 0xd2, (byte) 0xc2, (byte) 0x0f,
(byte) 0x9b, (byte) 0x92, (byte) 0x8f, (byte) 0xe2,
(byte) 0x27, (byte) 0x0d, (byte) 0x6f, (byte) 0xb8,
(byte) 0x63, (byte) 0xd5, (byte) 0x17, (byte) 0x38,
(byte) 0xb4, (byte) 0x8e, (byte) 0xee, (byte) 0xe3,
(byte) 0x14, (byte) 0xa7, (byte) 0xcc, (byte) 0x8a,
(byte) 0xb9, (byte) 0x32, (byte) 0x16, (byte) 0x45,
(byte) 0x48, (byte) 0xe5, (byte) 0x26, (byte) 0xae,
(byte) 0x90, (byte) 0x22, (byte) 0x43, (byte) 0x68,
(byte) 0x51, (byte) 0x7a, (byte) 0xcf, (byte) 0xea,
(byte) 0xbd, (byte) 0x6b, (byte) 0xb3, (byte) 0x73,
(byte) 0x2b, (byte) 0xc0, (byte) 0xe9, (byte) 0xda,
(byte) 0x99, (byte) 0x83, (byte) 0x2b, (byte) 0x61,
(byte) 0xca, (byte) 0x01, (byte) 0xb6, (byte) 0xde,
(byte) 0x56, (byte) 0x24, (byte) 0x4a, (byte) 0x9e,
(byte) 0x88, (byte) 0xd5, (byte) 0xf9, (byte) 0xb3,
(byte) 0x79, (byte) 0x73, (byte) 0xf6, (byte) 0x22,
(byte) 0xa4, (byte) 0x3d, (byte) 0x14, (byte) 0xa6,
(byte) 0x59, (byte) 0x9b, (byte) 0x1f, (byte) 0x65,
(byte) 0x4c, (byte) 0xb4, (byte) 0x5a, (byte) 0x74,
(byte) 0xe3, (byte) 0x55, (byte) 0xa5 };
final byte[] key = { (byte) 0xee, (byte) 0xa6, (byte) 0xa7, (byte) 0x25,
(byte) 0x1c, (byte) 0x1e, (byte) 0x72, (byte) 0x91,
(byte) 0x6d, (byte) 0x11, (byte) 0xc2, (byte) 0xcb,
(byte) 0x21, (byte) 0x4d, (byte) 0x3c, (byte) 0x25,
(byte) 0x25, (byte) 0x39, (byte) 0x12, (byte) 0x1d,
(byte) 0x8e, (byte) 0x23, (byte) 0x4e, (byte) 0x65,
(byte) 0x2d, (byte) 0x65, (byte) 0x1f, (byte) 0xa4,
(byte) 0xc8, (byte) 0xcf, (byte) 0xf8, (byte) 0x80 };
final byte[] ref = { (byte) 0xf3, (byte) 0xff, (byte) 0xc7, (byte) 0x70,
(byte) 0x3f, (byte) 0x94, (byte) 0x00, (byte) 0xe5,
(byte) 0x2a, (byte) 0x7d, (byte) 0xfb, (byte) 0x4b,
(byte) 0x3d, (byte) 0x33, (byte) 0x05, (byte) 0xd9 };
assertTrue("Invalid signature",Arrays.equals(ref,tweetnacl.cryptoOneTimeAuth(message,key)));
}
/**
* crypto_hash (adapted from tests/onetimeauth2.c)
*
*/
public void testCryptoOneTimeAuthVerify() throws Exception {
final byte[] auth = { (byte) 0xf3, (byte) 0xff, (byte) 0xc7, (byte) 0x70,
(byte) 0x3f, (byte) 0x94, (byte) 0x00, (byte) 0xe5,
(byte) 0x2a, (byte) 0x7d, (byte) 0xfb, (byte) 0x4b,
(byte) 0x3d, (byte) 0x33, (byte) 0x05, (byte) 0xd9 };
final byte[] message = { (byte) 0x8e, (byte) 0x99, (byte) 0x3b, (byte) 0x9f,
(byte) 0x48, (byte) 0x68, (byte) 0x12, (byte) 0x73,
(byte) 0xc2, (byte) 0x96, (byte) 0x50, (byte) 0xba,
(byte) 0x32, (byte) 0xfc, (byte) 0x76, (byte) 0xce,
(byte) 0x48, (byte) 0x33, (byte) 0x2e, (byte) 0xa7,
(byte) 0x16, (byte) 0x4d, (byte) 0x96, (byte) 0xa4,
(byte) 0x47, (byte) 0x6f, (byte) 0xb8, (byte) 0xc5,
(byte) 0x31, (byte) 0xa1, (byte) 0x18, (byte) 0x6a,
(byte) 0xc0, (byte) 0xdf, (byte) 0xc1, (byte) 0x7c,
(byte) 0x98, (byte) 0xdc, (byte) 0xe8, (byte) 0x7b,
(byte) 0x4d, (byte) 0xa7, (byte) 0xf0, (byte) 0x11,
(byte) 0xec, (byte) 0x48, (byte) 0xc9, (byte) 0x72,
(byte) 0x71, (byte) 0xd2, (byte) 0xc2, (byte) 0x0f,
(byte) 0x9b, (byte) 0x92, (byte) 0x8f, (byte) 0xe2,
(byte) 0x27, (byte) 0x0d, (byte) 0x6f, (byte) 0xb8,
(byte) 0x63, (byte) 0xd5, (byte) 0x17, (byte) 0x38,
(byte) 0xb4, (byte) 0x8e, (byte) 0xee, (byte) 0xe3,
(byte) 0x14, (byte) 0xa7, (byte) 0xcc, (byte) 0x8a,
(byte) 0xb9, (byte) 0x32, (byte) 0x16, (byte) 0x45,
(byte) 0x48, (byte) 0xe5, (byte) 0x26, (byte) 0xae,
(byte) 0x90, (byte) 0x22, (byte) 0x43, (byte) 0x68,
(byte) 0x51, (byte) 0x7a, (byte) 0xcf, (byte) 0xea,
(byte) 0xbd, (byte) 0x6b, (byte) 0xb3, (byte) 0x73,
(byte) 0x2b, (byte) 0xc0, (byte) 0xe9, (byte) 0xda,
(byte) 0x99, (byte) 0x83, (byte) 0x2b, (byte) 0x61,
(byte) 0xca, (byte) 0x01, (byte) 0xb6, (byte) 0xde,
(byte) 0x56, (byte) 0x24, (byte) 0x4a, (byte) 0x9e,
(byte) 0x88, (byte) 0xd5, (byte) 0xf9, (byte) 0xb3,
(byte) 0x79, (byte) 0x73, (byte) 0xf6, (byte) 0x22,
(byte) 0xa4, (byte) 0x3d, (byte) 0x14, (byte) 0xa6,
(byte) 0x59, (byte) 0x9b, (byte) 0x1f, (byte) 0x65,
(byte) 0x4c, (byte) 0xb4, (byte) 0x5a, (byte) 0x74,
(byte) 0xe3, (byte) 0x55, (byte) 0xa5 };
final byte[] key = { (byte) 0xee, (byte) 0xa6, (byte) 0xa7, (byte) 0x25,
(byte) 0x1c, (byte) 0x1e, (byte) 0x72, (byte) 0x91,
(byte) 0x6d, (byte) 0x11, (byte) 0xc2, (byte) 0xcb,
(byte) 0x21, (byte) 0x4d, (byte) 0x3c, (byte) 0x25,
(byte) 0x25, (byte) 0x39, (byte) 0x12, (byte) 0x1d,
(byte) 0x8e, (byte) 0x23, (byte) 0x4e, (byte) 0x65,
(byte) 0x2d, (byte) 0x65, (byte) 0x1f, (byte) 0xa4,
(byte) 0xc8, (byte) 0xcf, (byte) 0xf8, (byte) 0x80 };
assertTrue("Verify failed", tweetnacl.cryptoOneTimeAuthVerify(auth, message, key));
}
/**
* crypto_hash (adapted from tests/onetimeauth7.c)
*
*/
public void testCryptoOneTimeAuth7() throws Exception {
Random random = new Random();
for (int clen = 0; clen < ROUNDS; ++clen) {
byte[] key = new byte[TweetNaCl.ONETIMEAUTH_KEYBYTES];
byte[] message = new byte[clen];
byte[] auth;
random.nextBytes(key);
random.nextBytes(message);
auth = tweetnacl.cryptoOneTimeAuth(message, key);
assertNotNull(auth);
assertTrue(auth.length == TweetNaCl.ONETIMEAUTH_BYTES);
if (clen > 0) {
int mx = random.nextInt(clen);
int ax = random.nextInt(TweetNaCl.ONETIMEAUTH_BYTES);
byte[] m = message.clone();
byte[] a = auth.clone();
m[mx] = (byte) (message[mx] + 1 + random.nextInt(255));
a[ax] = (byte) (auth[ax] + 1 + random.nextInt(255));
assertFalse("Verified forgery with altered message",tweetnacl.cryptoOneTimeAuthVerify(auth, m, key));
assertFalse("Verified forgery with altered authentication",tweetnacl.cryptoOneTimeAuthVerify(a, message, key));
assertFalse("Verified forgery with altered message and authentication",tweetnacl.cryptoOneTimeAuthVerify(a, m, key));
}
}
}
}
| package za.IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3;
import java.IMPORT_4.IMPORT_5;
import java.IMPORT_4.IMPORT_6;
import za.IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_7;
public class CLASS_0 extends CLASS_1 {
// CONSTANTS
// UNIT TESTS
/**
* crypto_hash (adapted from tests/onetimeauth.c)
*
*/
public void FUNC_0() throws CLASS_2 {
final byte[] VAR_0 = { (byte) 0x8e, (byte) 0x99, (byte) 0x3b, (byte) 0x9f,
(byte) 0x48, (byte) 0x68, (byte) 0x12, (byte) 0x73,
(byte) 0xc2, (byte) 0x96, (byte) 0x50, (byte) 0xba,
(byte) 0x32, (byte) 0xfc, (byte) 0x76, (byte) 0xce,
(byte) 0x48, (byte) 0x33, (byte) 0x2e, (byte) 0xa7,
(byte) 0x16, (byte) 0x4d, (byte) 0x96, (byte) 0xa4,
(byte) 0x47, (byte) 0x6f, (byte) 0xb8, (byte) 0xc5,
(byte) 0x31, (byte) 0xa1, (byte) 0x18, (byte) 0x6a,
(byte) 0xc0, (byte) 0xdf, (byte) 0xc1, (byte) 0x7c,
(byte) 0x98, (byte) 0xdc, (byte) 0xe8, (byte) 0x7b,
(byte) 0x4d, (byte) 0xa7, (byte) 0xf0, (byte) 0x11,
(byte) 0xec, (byte) 0x48, (byte) 0xc9, (byte) 0x72,
(byte) 0x71, (byte) 0xd2, (byte) 0xc2, (byte) 0x0f,
(byte) 0x9b, (byte) 0x92, (byte) 0x8f, (byte) 0xe2,
(byte) 0x27, (byte) 0x0d, (byte) 0x6f, (byte) 0xb8,
(byte) 0x63, (byte) 0xd5, (byte) 0x17, (byte) 0x38,
(byte) 0xb4, (byte) 0x8e, (byte) 0xee, (byte) 0xe3,
(byte) 0x14, (byte) 0xa7, (byte) 0xcc, (byte) 0x8a,
(byte) 0xb9, (byte) 0x32, (byte) 0x16, (byte) 0x45,
(byte) 0x48, (byte) 0xe5, (byte) 0x26, (byte) 0xae,
(byte) 0x90, (byte) 0x22, (byte) 0x43, (byte) 0x68,
(byte) 0x51, (byte) 0x7a, (byte) 0xcf, (byte) 0xea,
(byte) 0xbd, (byte) 0x6b, (byte) 0xb3, (byte) 0x73,
(byte) 0x2b, (byte) 0xc0, (byte) 0xe9, (byte) 0xda,
(byte) 0x99, (byte) 0x83, (byte) 0x2b, (byte) 0x61,
(byte) 0xca, (byte) 0x01, (byte) 0xb6, (byte) 0xde,
(byte) 0x56, (byte) 0x24, (byte) 0x4a, (byte) 0x9e,
(byte) 0x88, (byte) 0xd5, (byte) 0xf9, (byte) 0xb3,
(byte) 0x79, (byte) 0x73, (byte) 0xf6, (byte) 0x22,
(byte) 0xa4, (byte) 0x3d, (byte) 0x14, (byte) 0xa6,
(byte) 0x59, (byte) 0x9b, (byte) 0x1f, (byte) 0x65,
(byte) 0x4c, (byte) 0xb4, (byte) 0x5a, (byte) 0x74,
(byte) 0xe3, (byte) 0x55, (byte) 0xa5 };
final byte[] VAR_1 = { (byte) 0xee, (byte) 0xa6, (byte) 0xa7, (byte) 0x25,
(byte) 0x1c, (byte) 0x1e, (byte) 0x72, (byte) 0x91,
(byte) 0x6d, (byte) 0x11, (byte) 0xc2, (byte) 0xcb,
(byte) 0x21, (byte) 0x4d, (byte) 0x3c, (byte) 0x25,
(byte) 0x25, (byte) 0x39, (byte) 0x12, (byte) 0x1d,
(byte) 0x8e, (byte) 0x23, (byte) 0x4e, (byte) 0x65,
(byte) 0x2d, (byte) 0x65, (byte) 0x1f, (byte) 0xa4,
(byte) 0xc8, (byte) 0xcf, (byte) 0xf8, (byte) 0x80 };
final byte[] ref = { (byte) 0xf3, (byte) 0xff, (byte) 0xc7, (byte) 0x70,
(byte) 0x3f, (byte) 0x94, (byte) 0x00, (byte) 0xe5,
(byte) 0x2a, (byte) 0x7d, (byte) 0xfb, (byte) 0x4b,
(byte) 0x3d, (byte) 0x33, (byte) 0x05, (byte) 0xd9 };
FUNC_1("Invalid signature",IMPORT_5.FUNC_2(ref,IMPORT_2.cryptoOneTimeAuth(VAR_0,VAR_1)));
}
/**
* crypto_hash (adapted from tests/onetimeauth2.c)
*
*/
public void FUNC_3() throws CLASS_2 {
final byte[] VAR_2 = { (byte) 0xf3, (byte) 0xff, (byte) 0xc7, (byte) 0x70,
(byte) 0x3f, (byte) 0x94, (byte) 0x00, (byte) 0xe5,
(byte) 0x2a, (byte) 0x7d, (byte) 0xfb, (byte) 0x4b,
(byte) 0x3d, (byte) 0x33, (byte) 0x05, (byte) 0xd9 };
final byte[] VAR_0 = { (byte) 0x8e, (byte) 0x99, (byte) 0x3b, (byte) 0x9f,
(byte) 0x48, (byte) 0x68, (byte) 0x12, (byte) 0x73,
(byte) 0xc2, (byte) 0x96, (byte) 0x50, (byte) 0xba,
(byte) 0x32, (byte) 0xfc, (byte) 0x76, (byte) 0xce,
(byte) 0x48, (byte) 0x33, (byte) 0x2e, (byte) 0xa7,
(byte) 0x16, (byte) 0x4d, (byte) 0x96, (byte) 0xa4,
(byte) 0x47, (byte) 0x6f, (byte) 0xb8, (byte) 0xc5,
(byte) 0x31, (byte) 0xa1, (byte) 0x18, (byte) 0x6a,
(byte) 0xc0, (byte) 0xdf, (byte) 0xc1, (byte) 0x7c,
(byte) 0x98, (byte) 0xdc, (byte) 0xe8, (byte) 0x7b,
(byte) 0x4d, (byte) 0xa7, (byte) 0xf0, (byte) 0x11,
(byte) 0xec, (byte) 0x48, (byte) 0xc9, (byte) 0x72,
(byte) 0x71, (byte) 0xd2, (byte) 0xc2, (byte) 0x0f,
(byte) 0x9b, (byte) 0x92, (byte) 0x8f, (byte) 0xe2,
(byte) 0x27, (byte) 0x0d, (byte) 0x6f, (byte) 0xb8,
(byte) 0x63, (byte) 0xd5, (byte) 0x17, (byte) 0x38,
(byte) 0xb4, (byte) 0x8e, (byte) 0xee, (byte) 0xe3,
(byte) 0x14, (byte) 0xa7, (byte) 0xcc, (byte) 0x8a,
(byte) 0xb9, (byte) 0x32, (byte) 0x16, (byte) 0x45,
(byte) 0x48, (byte) 0xe5, (byte) 0x26, (byte) 0xae,
(byte) 0x90, (byte) 0x22, (byte) 0x43, (byte) 0x68,
(byte) 0x51, (byte) 0x7a, (byte) 0xcf, (byte) 0xea,
(byte) 0xbd, (byte) 0x6b, (byte) 0xb3, (byte) 0x73,
(byte) 0x2b, (byte) 0xc0, (byte) 0xe9, (byte) 0xda,
(byte) 0x99, (byte) 0x83, (byte) 0x2b, (byte) 0x61,
(byte) 0xca, (byte) 0x01, (byte) 0xb6, (byte) 0xde,
(byte) 0x56, (byte) 0x24, (byte) 0x4a, (byte) 0x9e,
(byte) 0x88, (byte) 0xd5, (byte) 0xf9, (byte) 0xb3,
(byte) 0x79, (byte) 0x73, (byte) 0xf6, (byte) 0x22,
(byte) 0xa4, (byte) 0x3d, (byte) 0x14, (byte) 0xa6,
(byte) 0x59, (byte) 0x9b, (byte) 0x1f, (byte) 0x65,
(byte) 0x4c, (byte) 0xb4, (byte) 0x5a, (byte) 0x74,
(byte) 0xe3, (byte) 0x55, (byte) 0xa5 };
final byte[] VAR_1 = { (byte) 0xee, (byte) 0xa6, (byte) 0xa7, (byte) 0x25,
(byte) 0x1c, (byte) 0x1e, (byte) 0x72, (byte) 0x91,
(byte) 0x6d, (byte) 0x11, (byte) 0xc2, (byte) 0xcb,
(byte) 0x21, (byte) 0x4d, (byte) 0x3c, (byte) 0x25,
(byte) 0x25, (byte) 0x39, (byte) 0x12, (byte) 0x1d,
(byte) 0x8e, (byte) 0x23, (byte) 0x4e, (byte) 0x65,
(byte) 0x2d, (byte) 0x65, (byte) 0x1f, (byte) 0xa4,
(byte) 0xc8, (byte) 0xcf, (byte) 0xf8, (byte) 0x80 };
FUNC_1("Verify failed", IMPORT_2.FUNC_4(VAR_2, VAR_0, VAR_1));
}
/**
* crypto_hash (adapted from tests/onetimeauth7.c)
*
*/
public void FUNC_5() throws CLASS_2 {
IMPORT_6 VAR_3 = new IMPORT_6();
for (int VAR_4 = 0; VAR_4 < VAR_5; ++VAR_4) {
byte[] VAR_1 = new byte[IMPORT_7.VAR_6];
byte[] VAR_0 = new byte[VAR_4];
byte[] VAR_2;
VAR_3.FUNC_6(VAR_1);
VAR_3.FUNC_6(VAR_0);
VAR_2 = IMPORT_2.cryptoOneTimeAuth(VAR_0, VAR_1);
FUNC_7(VAR_2);
FUNC_1(VAR_2.VAR_7 == IMPORT_7.VAR_8);
if (VAR_4 > 0) {
int VAR_9 = VAR_3.nextInt(VAR_4);
int VAR_10 = VAR_3.nextInt(IMPORT_7.VAR_8);
byte[] VAR_11 = VAR_0.FUNC_8();
byte[] VAR_12 = VAR_2.FUNC_8();
VAR_11[VAR_9] = (byte) (VAR_0[VAR_9] + 1 + VAR_3.nextInt(255));
VAR_12[VAR_10] = (byte) (VAR_2[VAR_10] + 1 + VAR_3.nextInt(255));
FUNC_9("Verified forgery with altered message",IMPORT_2.FUNC_4(VAR_2, VAR_11, VAR_1));
FUNC_9("Verified forgery with altered authentication",IMPORT_2.FUNC_4(VAR_12, VAR_0, VAR_1));
FUNC_9("Verified forgery with altered message and authentication",IMPORT_2.FUNC_4(VAR_12, VAR_11, VAR_1));
}
}
}
}
| 0.833898 | {'IMPORT_0': 'co', 'IMPORT_1': 'twyst', 'IMPORT_2': 'tweetnacl', 'IMPORT_3': 'test', 'IMPORT_4': 'util', 'IMPORT_5': 'Arrays', 'IMPORT_6': 'Random', 'IMPORT_7': 'TweetNaCl', 'CLASS_0': 'TestCryptoOneTimeAuth', 'CLASS_1': 'TweetNaClTest', 'FUNC_0': 'testCryptoOneTimeAuth', 'CLASS_2': 'Exception', 'VAR_0': 'message', 'VAR_1': 'key', 'FUNC_1': 'assertTrue', 'FUNC_2': 'equals', 'FUNC_3': 'testCryptoOneTimeAuthVerify', 'VAR_2': 'auth', 'FUNC_4': 'cryptoOneTimeAuthVerify', 'FUNC_5': 'testCryptoOneTimeAuth7', 'VAR_3': 'random', 'VAR_4': 'clen', 'VAR_5': 'ROUNDS', 'VAR_6': 'ONETIMEAUTH_KEYBYTES', 'FUNC_6': 'nextBytes', 'FUNC_7': 'assertNotNull', 'VAR_7': 'length', 'VAR_8': 'ONETIMEAUTH_BYTES', 'VAR_9': 'mx', 'VAR_10': 'ax', 'VAR_11': 'm', 'FUNC_8': 'clone', 'VAR_12': 'a', 'FUNC_9': 'assertFalse'} | java | OOP | 45.59% |
/*
* Copyright (c) 2018 Tarokun LLC. All rights reserved.
*
* This file is part of BlobBase.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import org.blobbase.BlobBase;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import org.testng.annotations.Test;
/**
*
*/
public class BlobBaseMutiThreadTest
{
private static String TEST_DIR = "./dbMutiThreadTest/files";
public BlobBaseMutiThreadTest()
{
}
@org.testng.annotations.BeforeClass
public static void setUpClass() throws Exception
{
deleteFiles();
}
@org.testng.annotations.AfterClass
public static void tearDownClass()
{
}
@Test(priority = 1)
public void threadTest() throws Exception
{
int x = 0;
Worker[] workers = new Worker[100];
for (int i = 0; i < workers.length; i++)
{
workers[i] = new Worker(x++);
workers[i].start();
}
Thread.sleep(60000);
for (int i = 0; i < workers.length; i++)
{
Worker worker = workers[i];
worker.setStop(true);
}
Thread.sleep(1000);
for (int i = 0; i < workers.length; i++)
{
Worker worker = workers[i];
worker.join();
}
System.out.println("Done...");
}
private class Worker extends Thread
{
private boolean stop = false;
private int x = 0;
private int loopCnt = 100;
public Worker(int x)
{
this.x = x * loopCnt*10;
}
@SuppressWarnings("unchecked")
public void run()
{
try
{
File root = new File(TEST_DIR);
BlobBase map = BlobBase.getInstance(root);
String data = "Hello World ";
while (!stop)
{
Random random = new Random();
int delay = random.nextInt(1000);
Thread.sleep(delay);
for (int i = 0; i < loopCnt; i++)
{
String key = "key" + x + i;
File f1 = map.createFile(key);
assertNotNull(f1);
FileOutputStream fileOut = new FileOutputStream(f1);
String d = data + x + i;
fileOut.write(d.getBytes());
fileOut.close();
Map<String,Object> attrMap = new HashMap();
attrMap.put("testAttr", "123");
map.setAttributeMap(key, attrMap);
delay = random.nextInt(100);
Thread.sleep(delay);
}
delay = random.nextInt(1000);
Thread.sleep(delay);
for (int i = 0; i < loopCnt; i++)
{
String key = "key" + x + i;
File f1 = map.getFile(key);
assertNotNull(f1);
FileInputStream fileIn = new FileInputStream(f1);
byte[] buffer = new byte[(int)f1.length()];
fileIn.read(buffer);
String value = new String(buffer);
fileIn.close();
assertEquals(data + x + i, value);
Map<String,Object> attrMap = map.getAttributeMap(key);
String attrValue = (String)attrMap.get("testAttr");
assertEquals("123",attrValue);
delay = random.nextInt(100);
Thread.sleep(delay);
}
delay = random.nextInt(1000);
Thread.sleep(delay);
for (int i = 0; i < loopCnt; i++)
{
File f1 = map.getFile("key" + x + i);
assertNotNull(f1);
if (!f1.delete())
{
System.out.println("delete failed: key" + x + i);
}
delay = random.nextInt(100);
Thread.sleep(delay);
}
delay = random.nextInt(1000);
Thread.sleep(delay);
for (int i = 0; i < loopCnt; i++)
{
File f1 = map.getFile("key" + x + i);
if (f1 != null)
{
System.out.println("found key: key" + x + i);
System.out.println("file:"+f1.toString());
}
assertNull(f1);
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* @return the stop
*/
public boolean isStop()
{
return stop;
}
/**
* @param stop the stop to set
*/
public void setStop(boolean stop)
{
this.stop = stop;
}
}
private static void deleteFiles() throws Exception
{
System.out.println("deleting files in database");
File f = new File(TEST_DIR);
if (f.exists())
{
Path pathToBeDeleted = Paths.get(TEST_DIR);
Files.walk(pathToBeDeleted)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
f.mkdirs();
}
}
| /*
* Copyright (c) 2018 Tarokun LLC. All rights reserved.
*
* This file is part of BlobBase.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import org.IMPORT_0.IMPORT_1;
import java.IMPORT_2.IMPORT_3;
import java.IMPORT_2.IMPORT_4;
import java.IMPORT_2.FileOutputStream;
import java.IMPORT_5.IMPORT_6.IMPORT_7;
import java.IMPORT_5.IMPORT_6.IMPORT_8;
import java.IMPORT_5.IMPORT_6.Paths;
import java.IMPORT_9.IMPORT_10;
import java.IMPORT_9.IMPORT_11;
import java.IMPORT_9.IMPORT_12;
import java.IMPORT_9.IMPORT_13;
import static org.testng.IMPORT_14.IMPORT_15;
import static org.testng.IMPORT_14.IMPORT_16;
import static org.testng.IMPORT_14.IMPORT_17;
import static org.testng.IMPORT_14.IMPORT_18;
import org.testng.annotations.IMPORT_19;
/**
*
*/
public class CLASS_0
{
private static CLASS_1 VAR_0 = "./dbMutiThreadTest/files";
public CLASS_0()
{
}
@org.testng.annotations.IMPORT_20
public static void FUNC_0() throws CLASS_2
{
FUNC_1();
}
@org.testng.annotations.IMPORT_21
public static void FUNC_2()
{
}
@IMPORT_19(VAR_1 = 1)
public void FUNC_3() throws CLASS_2
{
int VAR_2 = 0;
Worker[] VAR_3 = new Worker[100];
for (int VAR_4 = 0; VAR_4 < VAR_3.VAR_5; VAR_4++)
{
VAR_3[VAR_4] = new Worker(VAR_2++);
VAR_3[VAR_4].FUNC_5();
}
VAR_6.FUNC_6(60000);
for (int VAR_4 = 0; VAR_4 < VAR_3.VAR_5; VAR_4++)
{
Worker VAR_7 = VAR_3[VAR_4];
VAR_7.FUNC_7(true);
}
VAR_6.FUNC_6(1000);
for (int VAR_4 = 0; VAR_4 < VAR_3.VAR_5; VAR_4++)
{
Worker VAR_7 = VAR_3[VAR_4];
VAR_7.FUNC_8();
}
VAR_8.VAR_9.FUNC_9("Done...");
}
private class Worker extends CLASS_3
{
private boolean VAR_10 = false;
private int VAR_2 = 0;
private int VAR_11 = 100;
public Worker(int VAR_2)
{
this.VAR_2 = VAR_2 * VAR_11*10;
}
@VAR_12("unchecked")
public void run()
{
try
{
IMPORT_3 VAR_13 = new IMPORT_3(VAR_0);
IMPORT_1 VAR_14 = IMPORT_1.getInstance(VAR_13);
CLASS_1 VAR_15 = "Hello World ";
while (!VAR_10)
{
IMPORT_13 VAR_16 = new IMPORT_13();
int VAR_17 = VAR_16.FUNC_11(1000);
VAR_6.FUNC_6(VAR_17);
for (int VAR_4 = 0; VAR_4 < VAR_11; VAR_4++)
{
CLASS_1 VAR_18 = "key" + VAR_2 + VAR_4;
IMPORT_3 VAR_19 = VAR_14.FUNC_12(VAR_18);
IMPORT_17(VAR_19);
FileOutputStream VAR_20 = new FileOutputStream(VAR_19);
CLASS_1 VAR_21 = VAR_15 + VAR_2 + VAR_4;
VAR_20.FUNC_13(VAR_21.FUNC_14());
VAR_20.close();
IMPORT_12<CLASS_1,CLASS_4> VAR_22 = new IMPORT_11();
VAR_22.FUNC_15("testAttr", "123");
VAR_14.setAttributeMap(VAR_18, VAR_22);
VAR_17 = VAR_16.FUNC_11(100);
VAR_6.FUNC_6(VAR_17);
}
VAR_17 = VAR_16.FUNC_11(1000);
VAR_6.FUNC_6(VAR_17);
for (int VAR_4 = 0; VAR_4 < VAR_11; VAR_4++)
{
CLASS_1 VAR_18 = "key" + VAR_2 + VAR_4;
IMPORT_3 VAR_19 = VAR_14.FUNC_16(VAR_18);
IMPORT_17(VAR_19);
IMPORT_4 VAR_23 = new IMPORT_4(VAR_19);
byte[] VAR_24 = new byte[(int)VAR_19.FUNC_4()];
VAR_23.FUNC_17(VAR_24);
CLASS_1 value = new CLASS_1(VAR_24);
VAR_23.close();
IMPORT_15(VAR_15 + VAR_2 + VAR_4, value);
IMPORT_12<CLASS_1,CLASS_4> VAR_22 = VAR_14.FUNC_18(VAR_18);
CLASS_1 VAR_25 = (CLASS_1)VAR_22.FUNC_19("testAttr");
IMPORT_15("123",VAR_25);
VAR_17 = VAR_16.FUNC_11(100);
VAR_6.FUNC_6(VAR_17);
}
VAR_17 = VAR_16.FUNC_11(1000);
VAR_6.FUNC_6(VAR_17);
for (int VAR_4 = 0; VAR_4 < VAR_11; VAR_4++)
{
IMPORT_3 VAR_19 = VAR_14.FUNC_16("key" + VAR_2 + VAR_4);
IMPORT_17(VAR_19);
if (!VAR_19.FUNC_20())
{
VAR_8.VAR_9.FUNC_9("delete failed: key" + VAR_2 + VAR_4);
}
VAR_17 = VAR_16.FUNC_11(100);
VAR_6.FUNC_6(VAR_17);
}
VAR_17 = VAR_16.FUNC_11(1000);
VAR_6.FUNC_6(VAR_17);
for (int VAR_4 = 0; VAR_4 < VAR_11; VAR_4++)
{
IMPORT_3 VAR_19 = VAR_14.FUNC_16("key" + VAR_2 + VAR_4);
if (VAR_19 != null)
{
VAR_8.VAR_9.FUNC_9("found key: key" + VAR_2 + VAR_4);
VAR_8.VAR_9.FUNC_9("file:"+VAR_19.FUNC_21());
}
IMPORT_18(VAR_19);
}
}
} catch (CLASS_2 VAR_27)
{
VAR_27.printStackTrace();
}
}
/**
* @return the stop
*/
public boolean FUNC_22()
{
return VAR_10;
}
/**
* @param stop the stop to set
*/
public void FUNC_7(boolean VAR_10)
{
this.VAR_10 = VAR_10;
}
}
private static void FUNC_1() throws CLASS_2
{
VAR_8.VAR_9.FUNC_9("deleting files in database");
IMPORT_3 f = new IMPORT_3(VAR_0);
if (f.FUNC_23())
{
IMPORT_8 VAR_28 = Paths.FUNC_19(VAR_0);
IMPORT_7.FUNC_24(VAR_28)
.sorted(IMPORT_10.reverseOrder())
.FUNC_10(IMPORT_8::toFile)
.FUNC_25(IMPORT_3::VAR_26);
IMPORT_16("Directory still exists", IMPORT_7.FUNC_23(VAR_28));
}
f.FUNC_26();
}
}
| 0.875716 | {'IMPORT_0': 'blobbase', 'IMPORT_1': 'BlobBase', 'IMPORT_2': 'io', 'IMPORT_3': 'File', 'IMPORT_4': 'FileInputStream', 'IMPORT_5': 'nio', 'IMPORT_6': 'file', 'IMPORT_7': 'Files', 'IMPORT_8': 'Path', 'IMPORT_9': 'util', 'IMPORT_10': 'Comparator', 'IMPORT_11': 'HashMap', 'IMPORT_12': 'Map', 'IMPORT_13': 'Random', 'IMPORT_14': 'AssertJUnit', 'IMPORT_15': 'assertEquals', 'IMPORT_16': 'assertFalse', 'IMPORT_17': 'assertNotNull', 'IMPORT_18': 'assertNull', 'IMPORT_19': 'Test', 'CLASS_0': 'BlobBaseMutiThreadTest', 'CLASS_1': 'String', 'VAR_0': 'TEST_DIR', 'IMPORT_20': 'BeforeClass', 'FUNC_0': 'setUpClass', 'CLASS_2': 'Exception', 'FUNC_1': 'deleteFiles', 'IMPORT_21': 'AfterClass', 'FUNC_2': 'tearDownClass', 'VAR_1': 'priority', 'FUNC_3': 'threadTest', 'VAR_2': 'x', 'VAR_3': 'workers', 'VAR_4': 'i', 'VAR_5': 'length', 'FUNC_4': 'length', 'FUNC_5': 'start', 'VAR_6': 'Thread', 'CLASS_3': 'Thread', 'FUNC_6': 'sleep', 'VAR_7': 'worker', 'FUNC_7': 'setStop', 'FUNC_8': 'join', 'VAR_8': 'System', 'VAR_9': 'out', 'FUNC_9': 'println', 'VAR_10': 'stop', 'VAR_11': 'loopCnt', 'VAR_12': 'SuppressWarnings', 'VAR_13': 'root', 'VAR_14': 'map', 'FUNC_10': 'map', 'VAR_15': 'data', 'VAR_16': 'random', 'VAR_17': 'delay', 'FUNC_11': 'nextInt', 'VAR_18': 'key', 'VAR_19': 'f1', 'FUNC_12': 'createFile', 'VAR_20': 'fileOut', 'VAR_21': 'd', 'FUNC_13': 'write', 'FUNC_14': 'getBytes', 'CLASS_4': 'Object', 'VAR_22': 'attrMap', 'FUNC_15': 'put', 'FUNC_16': 'getFile', 'VAR_23': 'fileIn', 'VAR_24': 'buffer', 'FUNC_17': 'read', 'FUNC_18': 'getAttributeMap', 'VAR_25': 'attrValue', 'FUNC_19': 'get', 'FUNC_20': 'delete', 'VAR_26': 'delete', 'FUNC_21': 'toString', 'VAR_27': 'e', 'FUNC_22': 'isStop', 'FUNC_23': 'exists', 'VAR_28': 'pathToBeDeleted', 'FUNC_24': 'walk', 'FUNC_25': 'forEach', 'FUNC_26': 'mkdirs'} | java | Hibrido | 53.37% |
/*
* Copyright (C) 2022 <NAME>
*
* GitHub Homepage: https://www.github.com/SteveJrong
* Gitee Homepage: https://gitee.com/stevejrong1024
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stevejrong.music.factory.common.util;
import com.stevejrong.music.factory.common.enums.BaseEnums;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Map;
/**
* HTTP工具类
*
* @author <NAME>
* @since 1.0
*/
public final class HttpUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
private static final ThreadLocal<OkHttpClient> httpClientThreadLocal = new ThreadLocal<OkHttpClient>();
/**
* 获取线程安全的OkHttpClient实例
*
* @return 线程安全的OkHttpClient实例
*/
private static OkHttpClient getOkHttpClientInstance() {
OkHttpClient httpClient = httpClientThreadLocal.get();
if (null == httpClient) {
httpClient = new OkHttpClient();
httpClientThreadLocal.set(httpClient);
}
return httpClient;
}
/**
* 发起GET请求(内部方法)
*
* @param url 请求地址
* @param headerParams 请求头参数,Map类型
* @param requestParams 请求体参数,Map类型
* @return ResponseBody响应体
*/
private static ResponseBody getSync(String url, Map<String, String> headerParams, Map<String, String> requestParams) {
ResponseBody result = null;
OkHttpClient httpClient = getOkHttpClientInstance();
Request.Builder requestBuilder = new Request.Builder();
if (null != headerParams && !headerParams.isEmpty()) {
// 添加请求头参数
headerParams.forEach(requestBuilder::addHeader);
}
// URL参数拼接
StringBuffer urlParamsStr = new StringBuffer("");
if (null != requestParams) {
urlParamsStr.append("?");
for (Map.Entry item : requestParams.entrySet()) {
urlParamsStr.append(item.getKey()).append("=").append(item.getValue()).append("&");
}
}
if (StringUtils.isNotBlank(urlParamsStr)) {
url = url + urlParamsStr.substring(0, urlParamsStr.length() - 1);
}
Request request = requestBuilder.url(url).build();
Call call = httpClient.newCall(request);
try {
Response response = call.execute();
result = response.body();
} catch (IOException e) {
LOGGER.error(LoggerUtil.builder().append("httpUtil_getSync", "发起GET请求(内部方法)")
.append("exception", e).append("exceptionMsg", e.getMessage()).toString());
}
return result;
}
/**
* 发起同步POST请求
*
* @param url 请求地址
* @param httpRequestBodyDataType HTTP请求的请求体数据类型
* @param headerParams 请求头参数,Map类型
* @param bodyParamsString 请求体参数,字符串类型
* @return ResponseBody响应体
*/
private static ResponseBody postSync(String url, BaseEnums.HttpRequestBodyDataType httpRequestBodyDataType, Map<String, String> headerParams, String bodyParamsString) {
ResponseBody result = null;
OkHttpClient httpClient = getOkHttpClientInstance();
// 添加请求头参数
Request.Builder requestBuilder = new Request.Builder();
if (null != headerParams && !headerParams.isEmpty()) {
headerParams.forEach(requestBuilder::addHeader);
}
// 创建RequestBody对象并使用JSON格式进行封装
RequestBody requestBody = null;
if (httpRequestBodyDataType == BaseEnums.HttpRequestBodyDataType.APPLICATION_JSON) {
requestBody = RequestBody.create(MediaType.parse(BaseEnums.HttpRequestBodyDataType.APPLICATION_JSON.getDesc()), bodyParamsString);
} else if (httpRequestBodyDataType == BaseEnums.HttpRequestBodyDataType.APPLICATION_XML) {
requestBody = RequestBody.create(MediaType.parse(BaseEnums.HttpRequestBodyDataType.APPLICATION_XML.getDesc()), bodyParamsString);
}
Request request = new Request.Builder().post(requestBody).url(url).build();
Call call = httpClient.newCall(request);
try {
Response response = call.execute();
result = response.body();
} catch (IOException e) {
LOGGER.error(LoggerUtil.builder().append("httpUtil_postSync", "发起同步POST请求")
.append("exception", e).append("exceptionMsg", e.getMessage()).toString());
}
return result;
}
/**
* 发起无请求头且带参的GET请求
*
* @param url 请求地址
* @param requestParams 请求体参数,Map类型
* @return 字符串格式的响应结果
*/
public static String get(String url, Map<String, String> requestParams) {
String result = null;
try {
result = getSync(url, null, requestParams).string();
} catch (IOException e) {
LOGGER.error(LoggerUtil.builder().append("httpUtil_get", "发起无请求头且带参的GET请求")
.append("exception", e).append("exceptionMsg", e.getMessage()).toString());
}
return result;
}
/**
* 发起无请求头、带参且用于获取URL图片为字节数组的GET请求
*
* @param url URL图片的请求地址
* @param requestParams 请求体参数,Map类型
* @return 图片字节数组
*/
public static byte[] getImage(String url, Map<String, String> requestParams) {
byte[] result = null;
try {
result = getSync(url, null, requestParams).bytes();
} catch (IOException e) {
LOGGER.error(LoggerUtil.builder().append("httpUtil_getImage", "发起无请求头、带参且用于获取URL图片为字节数组的GET请求")
.append("exception", e).append("exceptionMsg", e.getMessage()).toString());
}
return result;
}
/**
* 发起无请求头且带参的GET请求
* 用于获取二进制数据
*
* @param url 请求地址
* @param requestParams 请求体参数,Map类型
* @return 字符串格式的响应结果
*/
public static byte[] getOfBytes(String url, Map<String, String> requestParams) {
byte[] result = null;
try {
result = getSync(url, null, requestParams).bytes();
} catch (IOException e) {
LOGGER.error(LoggerUtil.builder().append("httpUtil_getOfBytes", "发起无请求头且带参的GET请求")
.append("exception", e).append("exceptionMsg", e.getMessage()).toString());
}
return result;
}
/**
* 发起有请求头的且带参的GET请求
*
* @param url 请求地址
* @param headerParams 请求头参数,Map类型
* @param requestParams 请求体参数,Map类型
* @return 字符串格式的响应结果
*/
public static Object get(String url, Map<String, String> headerParams, Map<String, String> requestParams) {
Object result = null;
try {
result = getSync(url, headerParams, requestParams).string();
} catch (IOException e) {
LOGGER.error(LoggerUtil.builder().append("httpUtil_get", "发起有请求头的且带参的GET请求")
.append("exception", e).append("exceptionMsg", e.getMessage()).toString());
}
return result;
}
/**
* 发起无请求头且带参的POST请求
*
* @param url 请求地址
* @param httpRequestBodyDataType HTTP请求的请求体数据类型
* @param bodyParamsString 请求体参数,字符串类型
* @return 字符串格式的响应结果
*/
public static String post(String url, BaseEnums.HttpRequestBodyDataType httpRequestBodyDataType, String bodyParamsString) {
String result = null;
try {
result = postSync(url, httpRequestBodyDataType, null, bodyParamsString).string();
} catch (IOException e) {
LOGGER.error(LoggerUtil.builder().append("httpUtil_post", "发起无请求头且带参的POST请求")
.append("exception", e).append("exceptionMsg", e.getMessage()).toString());
}
return result;
}
/**
* 发起有请求头且带参的POST请求
*
* @param url 请求地址
* @param httpRequestBodyDataType HTTP请求的请求体数据类型
* @param headerParams 请求头参数,Map类型
* @param bodyParamsString 请求体参数,字符串类型
* @return 字符串格式的响应结果
*/
public static String post(String url, BaseEnums.HttpRequestBodyDataType httpRequestBodyDataType, Map<String, String> headerParams, String bodyParamsString) {
String result = null;
try {
result = postSync(url, httpRequestBodyDataType, headerParams, bodyParamsString).string();
} catch (IOException e) {
LOGGER.error(LoggerUtil.builder().append("httpUtil_post", "发起有请求头且带参的POST请求")
.append("exception", e).append("exceptionMsg", e.getMessage()).toString());
}
return result;
}
}
| /*
* Copyright (C) 2022 <NAME>
*
* GitHub Homepage: https://www.github.com/SteveJrong
* Gitee Homepage: https://gitee.com/stevejrong1024
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.IMPORT_0.music.IMPORT_1.common.IMPORT_2;
import com.IMPORT_0.music.IMPORT_1.common.enums.IMPORT_3;
import okhttp3.*;
import IMPORT_4.IMPORT_5.IMPORT_6.IMPORT_7.IMPORT_8;
import IMPORT_4.IMPORT_9.Logger;
import IMPORT_4.IMPORT_9.LoggerFactory;
import java.io.IMPORT_10;
import java.IMPORT_2.IMPORT_11;
/**
* HTTP工具类
*
* @author <NAME>
* @since 1.0
*/
public final class HttpUtil {
private static final Logger VAR_0 = LoggerFactory.FUNC_0(HttpUtil.class);
private static final ThreadLocal<CLASS_0> VAR_1 = new ThreadLocal<CLASS_0>();
/**
* 获取线程安全的OkHttpClient实例
*
* @return 线程安全的OkHttpClient实例
*/
private static CLASS_0 FUNC_1() {
CLASS_0 VAR_2 = VAR_1.get();
if (null == VAR_2) {
VAR_2 = new CLASS_0();
VAR_1.FUNC_2(VAR_2);
}
return VAR_2;
}
/**
* 发起GET请求(内部方法)
*
* @param url 请求地址
* @param headerParams 请求头参数,Map类型
* @param requestParams 请求体参数,Map类型
* @return ResponseBody响应体
*/
private static CLASS_1 getSync(CLASS_2 VAR_3, IMPORT_11<CLASS_2, CLASS_2> VAR_4, IMPORT_11<CLASS_2, CLASS_2> VAR_5) {
CLASS_1 VAR_6 = null;
CLASS_0 VAR_2 = FUNC_1();
Request.CLASS_3 VAR_7 = new Request.CLASS_3();
if (null != VAR_4 && !VAR_4.isEmpty()) {
// 添加请求头参数
VAR_4.FUNC_4(VAR_7::VAR_8);
}
// URL参数拼接
CLASS_4 VAR_9 = new CLASS_4("");
if (null != VAR_5) {
VAR_9.FUNC_5("?");
for (IMPORT_11.Entry item : VAR_5.FUNC_6()) {
VAR_9.FUNC_5(item.FUNC_7()).FUNC_5("=").FUNC_5(item.FUNC_8()).FUNC_5("&");
}
}
if (IMPORT_8.FUNC_9(VAR_9)) {
VAR_3 = VAR_3 + VAR_9.FUNC_10(0, VAR_9.FUNC_11() - 1);
}
Request VAR_10 = VAR_7.FUNC_3(VAR_3).build();
CLASS_5 VAR_11 = VAR_2.FUNC_12(VAR_10);
try {
CLASS_6 response = VAR_11.FUNC_13();
VAR_6 = response.FUNC_14();
} catch (IMPORT_10 VAR_12) {
VAR_0.FUNC_15(VAR_13.FUNC_16().FUNC_5("httpUtil_getSync", "发起GET请求(内部方法)")
.FUNC_5("exception", VAR_12).FUNC_5("exceptionMsg", VAR_12.FUNC_17()).FUNC_18());
}
return VAR_6;
}
/**
* 发起同步POST请求
*
* @param url 请求地址
* @param httpRequestBodyDataType HTTP请求的请求体数据类型
* @param headerParams 请求头参数,Map类型
* @param bodyParamsString 请求体参数,字符串类型
* @return ResponseBody响应体
*/
private static CLASS_1 FUNC_19(CLASS_2 VAR_3, IMPORT_3.CLASS_7 httpRequestBodyDataType, IMPORT_11<CLASS_2, CLASS_2> VAR_4, CLASS_2 VAR_15) {
CLASS_1 VAR_6 = null;
CLASS_0 VAR_2 = FUNC_1();
// 添加请求头参数
Request.CLASS_3 VAR_7 = new Request.CLASS_3();
if (null != VAR_4 && !VAR_4.isEmpty()) {
VAR_4.FUNC_4(VAR_7::VAR_8);
}
// 创建RequestBody对象并使用JSON格式进行封装
CLASS_8 VAR_17 = null;
if (httpRequestBodyDataType == IMPORT_3.VAR_14.VAR_18) {
VAR_17 = VAR_16.FUNC_20(VAR_19.FUNC_21(IMPORT_3.VAR_14.VAR_18.FUNC_22()), VAR_15);
} else if (httpRequestBodyDataType == IMPORT_3.VAR_14.VAR_20) {
VAR_17 = VAR_16.FUNC_20(VAR_19.FUNC_21(IMPORT_3.VAR_14.VAR_20.FUNC_22()), VAR_15);
}
Request VAR_10 = new Request.CLASS_3().post(VAR_17).FUNC_3(VAR_3).build();
CLASS_5 VAR_11 = VAR_2.FUNC_12(VAR_10);
try {
CLASS_6 response = VAR_11.FUNC_13();
VAR_6 = response.FUNC_14();
} catch (IMPORT_10 VAR_12) {
VAR_0.FUNC_15(VAR_13.FUNC_16().FUNC_5("httpUtil_postSync", "发起同步POST请求")
.FUNC_5("exception", VAR_12).FUNC_5("exceptionMsg", VAR_12.FUNC_17()).FUNC_18());
}
return VAR_6;
}
/**
* 发起无请求头且带参的GET请求
*
* @param url 请求地址
* @param requestParams 请求体参数,Map类型
* @return 字符串格式的响应结果
*/
public static CLASS_2 get(CLASS_2 VAR_3, IMPORT_11<CLASS_2, CLASS_2> VAR_5) {
CLASS_2 VAR_6 = null;
try {
VAR_6 = getSync(VAR_3, null, VAR_5).FUNC_23();
} catch (IMPORT_10 VAR_12) {
VAR_0.FUNC_15(VAR_13.FUNC_16().FUNC_5("httpUtil_get", "发起无请求头且带参的GET请求")
.FUNC_5("exception", VAR_12).FUNC_5("exceptionMsg", VAR_12.FUNC_17()).FUNC_18());
}
return VAR_6;
}
/**
* 发起无请求头、带参且用于获取URL图片为字节数组的GET请求
*
* @param url URL图片的请求地址
* @param requestParams 请求体参数,Map类型
* @return 图片字节数组
*/
public static byte[] FUNC_24(CLASS_2 VAR_3, IMPORT_11<CLASS_2, CLASS_2> VAR_5) {
byte[] VAR_6 = null;
try {
VAR_6 = getSync(VAR_3, null, VAR_5).FUNC_25();
} catch (IMPORT_10 VAR_12) {
VAR_0.FUNC_15(VAR_13.FUNC_16().FUNC_5("httpUtil_getImage", "发起无请求头、带参且用于获取URL图片为字节数组的GET请求")
.FUNC_5("exception", VAR_12).FUNC_5("exceptionMsg", VAR_12.FUNC_17()).FUNC_18());
}
return VAR_6;
}
/**
* 发起无请求头且带参的GET请求
* 用于获取二进制数据
*
* @param url 请求地址
* @param requestParams 请求体参数,Map类型
* @return 字符串格式的响应结果
*/
public static byte[] getOfBytes(CLASS_2 VAR_3, IMPORT_11<CLASS_2, CLASS_2> VAR_5) {
byte[] VAR_6 = null;
try {
VAR_6 = getSync(VAR_3, null, VAR_5).FUNC_25();
} catch (IMPORT_10 VAR_12) {
VAR_0.FUNC_15(VAR_13.FUNC_16().FUNC_5("httpUtil_getOfBytes", "发起无请求头且带参的GET请求")
.FUNC_5("exception", VAR_12).FUNC_5("exceptionMsg", VAR_12.FUNC_17()).FUNC_18());
}
return VAR_6;
}
/**
* 发起有请求头的且带参的GET请求
*
* @param url 请求地址
* @param headerParams 请求头参数,Map类型
* @param requestParams 请求体参数,Map类型
* @return 字符串格式的响应结果
*/
public static Object get(CLASS_2 VAR_3, IMPORT_11<CLASS_2, CLASS_2> VAR_4, IMPORT_11<CLASS_2, CLASS_2> VAR_5) {
Object VAR_6 = null;
try {
VAR_6 = getSync(VAR_3, VAR_4, VAR_5).FUNC_23();
} catch (IMPORT_10 VAR_12) {
VAR_0.FUNC_15(VAR_13.FUNC_16().FUNC_5("httpUtil_get", "发起有请求头的且带参的GET请求")
.FUNC_5("exception", VAR_12).FUNC_5("exceptionMsg", VAR_12.FUNC_17()).FUNC_18());
}
return VAR_6;
}
/**
* 发起无请求头且带参的POST请求
*
* @param url 请求地址
* @param httpRequestBodyDataType HTTP请求的请求体数据类型
* @param bodyParamsString 请求体参数,字符串类型
* @return 字符串格式的响应结果
*/
public static CLASS_2 post(CLASS_2 VAR_3, IMPORT_3.CLASS_7 httpRequestBodyDataType, CLASS_2 VAR_15) {
CLASS_2 VAR_6 = null;
try {
VAR_6 = FUNC_19(VAR_3, httpRequestBodyDataType, null, VAR_15).FUNC_23();
} catch (IMPORT_10 VAR_12) {
VAR_0.FUNC_15(VAR_13.FUNC_16().FUNC_5("httpUtil_post", "发起无请求头且带参的POST请求")
.FUNC_5("exception", VAR_12).FUNC_5("exceptionMsg", VAR_12.FUNC_17()).FUNC_18());
}
return VAR_6;
}
/**
* 发起有请求头且带参的POST请求
*
* @param url 请求地址
* @param httpRequestBodyDataType HTTP请求的请求体数据类型
* @param headerParams 请求头参数,Map类型
* @param bodyParamsString 请求体参数,字符串类型
* @return 字符串格式的响应结果
*/
public static CLASS_2 post(CLASS_2 VAR_3, IMPORT_3.CLASS_7 httpRequestBodyDataType, IMPORT_11<CLASS_2, CLASS_2> VAR_4, CLASS_2 VAR_15) {
CLASS_2 VAR_6 = null;
try {
VAR_6 = FUNC_19(VAR_3, httpRequestBodyDataType, VAR_4, VAR_15).FUNC_23();
} catch (IMPORT_10 VAR_12) {
VAR_0.FUNC_15(VAR_13.FUNC_16().FUNC_5("httpUtil_post", "发起有请求头且带参的POST请求")
.FUNC_5("exception", VAR_12).FUNC_5("exceptionMsg", VAR_12.FUNC_17()).FUNC_18());
}
return VAR_6;
}
}
| 0.736108 | {'IMPORT_0': 'stevejrong', 'IMPORT_1': 'factory', 'IMPORT_2': 'util', 'IMPORT_3': 'BaseEnums', 'IMPORT_4': 'org', 'IMPORT_5': 'apache', 'IMPORT_6': 'commons', 'IMPORT_7': 'lang3', 'IMPORT_8': 'StringUtils', 'IMPORT_9': 'slf4j', 'IMPORT_10': 'IOException', 'IMPORT_11': 'Map', 'VAR_0': 'LOGGER', 'FUNC_0': 'getLogger', 'CLASS_0': 'OkHttpClient', 'VAR_1': 'httpClientThreadLocal', 'FUNC_1': 'getOkHttpClientInstance', 'VAR_2': 'httpClient', 'FUNC_2': 'set', 'CLASS_1': 'ResponseBody', 'CLASS_2': 'String', 'VAR_3': 'url', 'FUNC_3': 'url', 'VAR_4': 'headerParams', 'VAR_5': 'requestParams', 'VAR_6': 'result', 'CLASS_3': 'Builder', 'VAR_7': 'requestBuilder', 'FUNC_4': 'forEach', 'VAR_8': 'addHeader', 'CLASS_4': 'StringBuffer', 'VAR_9': 'urlParamsStr', 'FUNC_5': 'append', 'FUNC_6': 'entrySet', 'FUNC_7': 'getKey', 'FUNC_8': 'getValue', 'FUNC_9': 'isNotBlank', 'FUNC_10': 'substring', 'FUNC_11': 'length', 'VAR_10': 'request', 'CLASS_5': 'Call', 'VAR_11': 'call', 'FUNC_12': 'newCall', 'CLASS_6': 'Response', 'FUNC_13': 'execute', 'FUNC_14': 'body', 'VAR_12': 'e', 'FUNC_15': 'error', 'VAR_13': 'LoggerUtil', 'FUNC_16': 'builder', 'FUNC_17': 'getMessage', 'FUNC_18': 'toString', 'FUNC_19': 'postSync', 'CLASS_7': 'HttpRequestBodyDataType', 'VAR_14': 'HttpRequestBodyDataType', 'VAR_15': 'bodyParamsString', 'CLASS_8': 'RequestBody', 'VAR_16': 'RequestBody', 'VAR_17': 'requestBody', 'VAR_18': 'APPLICATION_JSON', 'FUNC_20': 'create', 'VAR_19': 'MediaType', 'FUNC_21': 'parse', 'FUNC_22': 'getDesc', 'VAR_20': 'APPLICATION_XML', 'FUNC_23': 'string', 'FUNC_24': 'getImage', 'FUNC_25': 'bytes'} | java | Hibrido | 17.21% |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package tests.unit.com.microsoft.azure.sdk.iot.device;
import com.microsoft.azure.sdk.iot.device.*;
import com.microsoft.azure.sdk.iot.device.DeviceTwin.*;
import com.microsoft.azure.sdk.iot.device.auth.IotHubSasTokenAuthenticationProvider;
import com.microsoft.azure.sdk.iot.device.auth.IotHubX509AuthenticationProvider;
import com.microsoft.azure.sdk.iot.device.exceptions.TransportException;
import com.microsoft.azure.sdk.iot.device.fileupload.FileUpload;
import com.microsoft.azure.sdk.iot.device.transport.ExponentialBackoffWithJitter;
import com.microsoft.azure.sdk.iot.device.transport.RetryPolicy;
import com.microsoft.azure.sdk.iot.device.transport.amqps.IoTHubConnectionType;
import com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider;
import com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException;
import mockit.*;
import org.junit.Test;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Unit tests for DeviceClient.
* Methods: 100%
* Lines: 96%
*/
public class DeviceClientTest
{
@Mocked
DeviceClientConfig mockConfig;
@Mocked
IotHubConnectionString mockIotHubConnectionString;
@Mocked
DeviceIO mockDeviceIO;
@Mocked
TransportClient mockTransportClient;
@Mocked
FileUpload mockFileUpload;
@Mocked
IotHubSasTokenAuthenticationProvider mockIotHubSasTokenAuthenticationProvider;
@Mocked
IotHubX509AuthenticationProvider mockIotHubX509AuthenticationProvider;
@Mocked
SecurityProvider mockSecurityProvider;
@Mocked
IotHubConnectionStatusChangeCallback mockedIotHubConnectionStatusChangeCallback;
@Mocked
ProductInfo mockedProductInfo;
private static long SEND_PERIOD_MILLIS = 10L;
private static long RECEIVE_PERIOD_MILLIS_AMQPS = 10L;
private static long RECEIVE_PERIOD_MILLIS_HTTPS = 25*60*1000; /*25 minutes*/
private void deviceClientInstanceExpectation(final String connectionString, final IotHubClientProtocol protocol)
{
final long receivePeriod;
switch (protocol)
{
case HTTPS:
receivePeriod = RECEIVE_PERIOD_MILLIS_HTTPS;
break;
default:
receivePeriod = RECEIVE_PERIOD_MILLIS_AMQPS;
break;
}
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(IotHubConnectionString.class, connectionString);
result = mockIotHubConnectionString;
Deencapsulation.newInstance(DeviceClientConfig.class, mockIotHubConnectionString, DeviceClientConfig.AuthType.SAS_TOKEN);
result = mockConfig;
Deencapsulation.newInstance(DeviceIO.class,
mockConfig, SEND_PERIOD_MILLIS, receivePeriod);
result = mockDeviceIO;
}
};
}
// Tests_SRS_DEVICECLIENT_12_009: [The constructor shall interpret the connection string as a set of key-value pairs delimited by ';', using the object IotHubConnectionString.]
// Tests_SRS_DEVICECLIENT_12_010: [The constructor shall set the connection type to USE_TRANSPORTCLIENT.]
// Tests_SRS_DEVICECLIENT_12_011: [The constructor shall set the deviceIO to null.]
// Tests_SRS_DEVICECLIENT_12_016: [The constructor shall save the transportClient parameter.]
// Tests_SRS_DEVICECLIENT_12_017: [The constructor shall register the device client with the transport client.]
@Test
public void constructorTransportClientSuccess() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>;";
// act
final DeviceClient client = new DeviceClient(connString, mockTransportClient);
// assert
new Verifications()
{
{
IotHubConnectionString iotHubConnectionString = Deencapsulation.newInstance(IotHubConnectionString.class, connString);
times = 1;
Deencapsulation.newInstance(DeviceClientConfig.class, iotHubConnectionString, DeviceClientConfig.AuthType.SAS_TOKEN);
times = 1;
IoTHubConnectionType ioTHubConnectionType = Deencapsulation.getField(client, "ioTHubConnectionType");
assertEquals(IoTHubConnectionType.USE_TRANSPORTCLIENT, ioTHubConnectionType);
DeviceIO deviceIO = Deencapsulation.getField(client, "deviceIO");
assertNull(deviceIO);
TransportClient actualTransportClient = Deencapsulation.getField(client, "transportClient");
assertEquals(mockTransportClient, actualTransportClient);
Deencapsulation.invoke(mockTransportClient, "registerDeviceClient", client);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_008: [If the connection string is null or empty, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void constructorTransportClientNullConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = null;
// act
new DeviceClient(connString, mockTransportClient);
}
// Tests_SRS_DEVICECLIENT_12_008: [If the connection string is null or empty, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void constructorTransportClientEmptyConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = "";
// act
new DeviceClient(connString, mockTransportClient);
}
// Tests_SRS_DEVICECLIENT_12_018: [If the tranportClient is null, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void constructorTransportClientTransportClientNullThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>;";
// act
new DeviceClient(connString, (TransportClient) null);
}
/* Tests_SRS_DEVICECLIENT_21_001: [The constructor shall interpret the connection string as a set of key-value pairs delimited by ';', using the object IotHubConnectionString.] */
/* Tests_SRS_DEVICECLIENT_21_002: [The constructor shall initialize the IoT Hub transport for the protocol specified, creating a instance of the deviceIO.] */
/* Tests_SRS_DEVICECLIENT_21_003: [The constructor shall save the connection configuration using the object DeviceClientConfig.] */
@Test
public void constructorSuccess() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>=;";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
final DeviceClient client = new DeviceClient(connString, protocol);
// assert
new Verifications()
{
{
IotHubConnectionString iotHubConnectionString = Deencapsulation.newInstance(IotHubConnectionString.class, connString);
times = 1;
Deencapsulation.newInstance(DeviceClientConfig.class, iotHubConnectionString, DeviceClientConfig.AuthType.SAS_TOKEN);
times = 1;
// Tests_SRS_DEVICECLIENT_12_012: [The constructor shall set the connection type to SINGLE_CLIENT.]
IoTHubConnectionType ioTHubConnectionType = Deencapsulation.getField(client, "ioTHubConnectionType");
assertEquals(IoTHubConnectionType.SINGLE_CLIENT, ioTHubConnectionType);
// Tests_SRS_DEVICECLIENT_12_015: [The constructor shall set the transportClient to null.]
TransportClient transportClient = Deencapsulation.getField(client, "transportClient");
assertNull(transportClient);
}
};
}
//Tests_SRS_DEVICECLIENT_34_058: [The constructor shall interpret the connection string as a set of key-value pairs delimited by ';', using the object IotHubConnectionString.]
//Tests_SRS_DEVICECLIENT_34_059: [The constructor shall initialize the IoT Hub transport for the protocol specified, creating a instance of the deviceIO.]
//Tests_SRS_DEVICECLIENT_34_060: [The constructor shall save the connection configuration using the object DeviceClientConfig.]
//Tests_SRS_DEVICECLIENT_34_063: [This function shall save the provided certificate and key within its config.]
@Test
public void constructorSuccessX509() throws URISyntaxException, IOException
{
// arrange
final String publicKeyCert = "someCert";
final String privateKey = "someKey";
final String connString =
"HostName=iothub.device.com;DeviceId=testdevice;x509=true";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS_WS;
new NonStrictExpectations()
{
{
mockIotHubConnectionString.isUsingX509();
result = true;
}
};
// act
final DeviceClient client = new DeviceClient(connString, protocol, publicKeyCert, false, privateKey, false);
// assert
new Verifications()
{
{
Deencapsulation.newInstance(IotHubConnectionString.class, connString);
times = 1;
new DeviceClientConfig((IotHubConnectionString) any, publicKeyCert, false, privateKey, false);
times = 1;
// Tests_SRS_DEVICECLIENT_12_013: [The constructor shall set the connection type to SINGLE_CLIENT.]
IoTHubConnectionType ioTHubConnectionType = Deencapsulation.getField(client, "ioTHubConnectionType");
assertEquals(IoTHubConnectionType.SINGLE_CLIENT, ioTHubConnectionType);
// Tests_SRS_DEVICECLIENT_12_014: [The constructor shall set the transportClient to null.]
TransportClient transportClient = Deencapsulation.getField(client, "transportClient");
assertNull(transportClient);
}
};
}
/* Tests_SRS_DEVICECLIENT_21_004: [If the connection string is null or empty, the function shall throw an IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void constructorNullConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = null;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol);
}
//Tests_SRS_DEVICECLIENT_34_061: [If the connection string is null or empty, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void x509ConstructorNullConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = null;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol, "any cert", false, "any key", false);
}
//Tests_SRS_DEVICECLIENT_34_064: [If the provided protocol is null, this function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void createFromSecurityProviderThrowsForNullProtocol() throws URISyntaxException, SecurityProviderException, IOException
{
//act
DeviceClient.createFromSecurityProvider("some uri", "some device id", mockSecurityProvider, null);
}
//Tests_SRS_DEVICECLIENT_34_065: [The provided uri and device id will be used to create an iotHubConnectionString that will be saved in config.]
//Tests_SRS_DEVICECLIENT_34_066: [The provided security provider will be saved in config.]
//Tests_SRS_DEVICECLIENT_34_067: [The constructor shall initialize the IoT Hub transport for the protocol specified, creating a instance of the deviceIO.]
@Test
public void createFromSecurityProviderUsesUriAndDeviceIdAndSavesSecurityProviderAndCreatesDeviceIO() throws URISyntaxException, SecurityProviderException, IOException
{
//arrange
final String expectedUri = "some uri";
final String expectedDeviceId = "some device id";
final IotHubClientProtocol expectedProtocol = IotHubClientProtocol.HTTPS;
new StrictExpectations()
{
{
new IotHubConnectionString(expectedUri, expectedDeviceId, null, null);
result = mockIotHubConnectionString;
}
};
//act
DeviceClient.createFromSecurityProvider(expectedUri, expectedDeviceId, mockSecurityProvider, expectedProtocol);
//assert
new Verifications()
{
{
Deencapsulation.newInstance(DeviceClientConfig.class, new Class[] {IotHubConnectionString.class, SecurityProvider.class}, mockIotHubConnectionString, mockSecurityProvider);
times = 1;
Deencapsulation.newInstance("com.microsoft.azure.sdk.iot.device.DeviceIO",
new Class[] {DeviceClientConfig.class, long.class, long.class},
any, SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_HTTPS);
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_004: [If the connection string is null or empty, the function shall throw an IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void constructorEmptyConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = "";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol);
}
//Tests_SRS_DEVICECLIENT_34_062: [If protocol is null, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void x509ConstructorEmptyConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = "";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol, "any cert", false, "any key", false);
}
/* Tests_SRS_DEVICECLIENT_21_005: [If protocol is null, the function shall throw an IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void constructorNullProtocolThrows() throws URISyntaxException, IOException
{
// arrange
final String connString =
"HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>=;";
final IotHubClientProtocol protocol = null;
// act
new DeviceClient(connString, protocol);
}
/* Tests_SRS_DEVICECLIENT_21_001: [The constructor shall interpret the connection string as a set of key-value pairs delimited by ';', using the object IotHubConnectionString.] */
@Test
public void constructorBadConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString =
"HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>;";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(IotHubConnectionString.class, connString);
result = new IllegalArgumentException();
}
};
// act
try
{
new DeviceClient(connString, protocol);
}
catch (IllegalArgumentException expected)
{
// Don't do anything, throw expected.
}
// assert
new Verifications()
{
{
IotHubConnectionString iotHubConnectionString = Deencapsulation.newInstance(IotHubConnectionString.class, connString);
times = 1;
Deencapsulation.newInstance(DeviceClientConfig.class, iotHubConnectionString, DeviceClientConfig.AuthType.SAS_TOKEN);
times = 0;
Deencapsulation.newInstance("com.microsoft.azure.sdk.iot.device.DeviceIO",
new Class[] {DeviceClientConfig.class, long.class, long.class},
any, SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_AMQPS);
times = 0;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_002: [The constructor shall initialize the IoT Hub transport for the protocol specified, creating a instance of the deviceIO.] */
@Test (expected = IllegalArgumentException.class)
public void constructorBadDeviceIOThrows() throws URISyntaxException, IOException
{
// arrange
final String connString =
"HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>;";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol);
// assert
new Verifications()
{
{
Deencapsulation.newInstance(IotHubConnectionString.class, connString);
times = 1;
Deencapsulation.newInstance(DeviceClientConfig.class, (IotHubConnectionString)any, DeviceClientConfig.AuthType.SAS_TOKEN);
times = 1;
Deencapsulation.newInstance("com.microsoft.azure.sdk.iot.device.DeviceIO",
new Class[] {DeviceClientConfig.class, IotHubClientProtocol.class, long.class, long.class},
(DeviceClientConfig)any, protocol, SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_AMQPS);
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_003: [The constructor shall save the connection configuration using the object DeviceClientConfig.] */
@Test (expected = IllegalArgumentException.class)
public void constructorBadDeviceClientConfigThrows() throws URISyntaxException, IOException
{
// arrange
final String connString =
"HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>;";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol);
// assert
new Verifications()
{
{
Deencapsulation.newInstance(DeviceClientConfig.class, (IotHubConnectionString)any, DeviceClientConfig.AuthType.SAS_TOKEN);
times = 1;
Deencapsulation.newInstance("com.microsoft.azure.sdk.iot.device.DeviceIO",
new Class[] {DeviceClientConfig.class, IotHubClientProtocol.class, long.class, long.class},
(DeviceClientConfig)any, protocol, SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_AMQPS);
times = 0;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_006: [The open shall open the deviceIO connection.] */
@Test
public void openOpensDeviceIOSuccess() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.open();
// assert
new Verifications()
{
{
Deencapsulation.newInstance("com.microsoft.azure.sdk.iot.device.DeviceIO",
new Class[] {DeviceClientConfig.class, long.class, long.class},
any, SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_AMQPS);
times = 1;
Deencapsulation.invoke(mockDeviceIO, "open");
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_007: [If the client has been initialized to use TransportClient and the TransportClient is not opened yet the function shall throw an IOException.]
@Test (expected = IOException.class)
public void openUseTransportClientAndCalledBeforeTransportClientOpenedThrows() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.CLOSED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
client.open();
}
// Tests_SRS_DEVICECLIENT_12_019: [If the client has been initialized to use TransportClient and the TransportClient is already opened the function shall do nothing.]
@Test
public void openUseTransportClientAndCalledAfterTransportClientOpenedDoNothing() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
// act
client.open();
new Verifications()
{
{
Deencapsulation.invoke(mockDeviceIO, "open");
times = 0;
}
};
}
/* Tests_SRS_DEVICECLIENT_11_040: [The function shall finish all ongoing tasks.] */
/* Tests_SRS_DEVICECLIENT_11_041: [The function shall cancel all recurring tasks.] */
/* Tests_SRS_DEVICECLIENT_21_042: [The closeNow shall closeNow the deviceIO connection.] */
/* Tests_SRS_DEVICECLIENT_21_043: [If the closing a connection via deviceIO is not successful, the closeNow shall throw IOException.] */
@Test
public void closeClosesTransportSuccess() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
new NonStrictExpectations()
{
{
mockDeviceIO.isEmpty();
result = true;
}
};
// act
client.close();
// assert
new Verifications()
{
{
mockDeviceIO.isEmpty();
times = 1;
mockDeviceIO.close();
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_11_040: [The function shall finish all ongoing tasks.] */
/* Tests_SRS_DEVICECLIENT_11_041: [The function shall cancel all recurring tasks.] */
/* Tests_SRS_DEVICECLIENT_21_042: [The closeNow shall closeNow the deviceIO connection.] */
/* Tests_SRS_DEVICECLIENT_21_043: [If the closing a connection via deviceIO is not successful, the closeNow shall throw IOException.] */
@Test
public void closeWaitAndClosesTransportSuccess() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
new NonStrictExpectations()
{
{
mockDeviceIO.isEmpty();
returns(false, false, true);
}
};
// act
client.close();
// assert
new Verifications()
{
{
mockDeviceIO.isEmpty();
times = 3;
mockDeviceIO.close();
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_006: [If the client has been initialized to use TransportClient and the TransportClient is already opened the function shall throw an IOException.]
@Test (expected = IOException.class)
public void closeUseTransportClientAndCalledAfterTransportClientOpenedThrows() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
client.close();
}
// Tests_SRS_DEVICECLIENT_12_020: [If the client has been initialized to use TransportClient and the TransportClient is not opened yet the function shall do nothing.]
@Test
public void closeUseTransportClientAndCalledBeforeTransportClientOpenedDoNothing() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.CLOSED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
// act
client.close();
new Verifications()
{
{
mockDeviceIO.isEmpty();
times = 0;
mockDeviceIO.close();
times = 0;
}
};
}
// Tests_SRS_DEVICECLIENT_12_005: [If the client has been initialized to use TransportClient and the TransportClient is already opened the function shall throw an IOException.]
@Test (expected = IOException.class)
public void closeNowUseTransportClientAndCalledAfterTransportClientOpenedThrows() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
client.closeNow();
}
// Tests_SRS_DEVICECLIENT_12_021: [If the client has been initialized to use TransportClient and the TransportClient is not opened yet the function shall do nothing.]
@Test
public void closeNowUseTransportClientAndCalledBeforeTransportClientOpenedDoNothing() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.CLOSED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
Deencapsulation.setField(client, "fileUpload", mockFileUpload);
// act
client.closeNow();
new Verifications()
{
{
mockFileUpload.closeNow();
times = 0;
mockDeviceIO.close();
times = 0;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_008: [The closeNow shall closeNow the deviceIO connection.] */
@Test
public void closeNowClosesTransportSuccess() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
// act
client.closeNow();
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_009: [If the closing a connection via deviceIO is not successful, the closeNow shall throw IOException.] */
@Test
public void closeNowBadCloseTransportThrows() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.close();
result = new IOException();
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
// act
try
{
client.closeNow();
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_010: [The sendEventAsync shall asynchronously send the message using the deviceIO connection.] */
@Test
public void sendEventAsyncSendsSuccess(
@Mocked final Message mockMessage,
@Mocked final IotHubEventCallback mockCallback)
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final Map<String, Object> context = new HashMap<>();
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
client.open();
// act
client.sendEventAsync(mockMessage, mockCallback, context);
// assert
new Verifications()
{
{
mockDeviceIO.sendEventAsync(mockMessage, mockCallback, context, mockConfig.getIotHubConnectionString());
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_011: [If starting to send via deviceIO is not successful, the sendEventAsync shall bypass the threw exception.] */
// Tests_SRS_DEVICECLIENT_12_001: [The function shall call deviceIO.sendEventAsync with the client's config parameter to enable multiplexing.]
@Test
public void sendEventAsyncBadSendThrows(
@Mocked final Message mockMessage,
@Mocked final IotHubEventCallback mockCallback)
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final Map<String, Object> context = new HashMap<>();
new NonStrictExpectations()
{
{
mockDeviceIO.sendEventAsync(mockMessage, mockCallback, context, null);
result = new IllegalStateException();
}
};
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
client.open();
// act
try
{
client.sendEventAsync(mockMessage, mockCallback, context);
}
catch (IllegalStateException expected)
{
// Don't do anything, throw expected.
}
// assert
new Verifications()
{
{
mockDeviceIO.sendEventAsync(mockMessage, mockCallback, context, mockConfig.getIotHubConnectionString());
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_11_013: [The function shall set the message callback, with its associated context.]
// Tests_SRS_DEVICECLIENT_12_001: [The function shall call deviceIO.sendEventAsync with the client's config parameter to enable multiplexing.]
@Test
public void setMessageCallbackSetsMessageCallback(
@Mocked final MessageCallback mockCallback)
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>=";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final Map<String, Object> context = new HashMap<>();
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setMessageCallback(mockCallback, context);
// assert
new Verifications()
{
{
mockConfig.setMessageCallback(mockCallback, context);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_11_014: [If the callback is null but the context is non-null, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void setMessageCallbackRejectsNullCallbackAndNonnullContext()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final Map<String, Object> context = new HashMap<>();
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setMessageCallback(null, context);
}
/*
**Tests_SRS_DEVICECLIENT_25_025: [**The function shall create a new instance of class Device Twin and request all twin properties by calling getDeviceTwin**]**
*/
@Test
public void startDeviceTwinSucceeds(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//assert
new Verifications()
{
{
mockedDeviceTwin.getDeviceTwin();
times = 1;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_026: [**If the deviceTwinStatusCallback or genericPropertyCallBack is null, the function shall throw an InvalidParameterException.**]**
*/
@Test (expected = IllegalArgumentException.class)
public void startDeviceTwinThrowsIfStatusCBisNull(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.startDeviceTwin(null, null, mockedPropertyCB, null);
//assert
new Verifications()
{
{
mockedDeviceTwin.getDeviceTwin();
times = 0;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_026: [**If the deviceTwinStatusCallback or genericPropertyCallBack is null, the function shall throw an InvalidParameterException.**]**
*/
@Test (expected = IllegalArgumentException.class)
public void startDeviceTwinThrowsIfPropCBisNull(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.startDeviceTwin(mockedStatusCB, null, (PropertyCallBack) null, null);
}
/*
**Tests_SRS_DEVICECLIENT_25_028: [**If this method is called twice on the same instance of the client then this method shall throw UnsupportedOperationException.**]**
*/
@Test
public void startDeviceTwinThrowsIfCalledTwice(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
try
{
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
}
catch (UnsupportedOperationException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.getDeviceTwin();
times = 1;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_027: [**If the client has not been open, the function shall throw an IOException.**]**
*/
@Test (expected = IOException.class)
public void startDeviceTwinThrowsIfCalledWhenClientNotOpen(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
//act
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
}
/*
**Tests_SRS_DEVICECLIENT_25_031: [**This method shall subscribe to desired properties by calling subscribeDesiredPropertiesNotification on the twin object.**]**
*/
@Test
public void subscribeToDPSucceeds(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB,
@Mocked final Map<Property, Pair<PropertyCallBack<String, Object>, Object>> mockMap) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
client.subscribeToDesiredProperties(mockMap);
//assert
new Verifications()
{
{
mockedDeviceTwin.subscribeDesiredPropertiesNotification(mockMap);
times = 1;
}
};
}
@Test
public void subscribeToDPWorksWhenMapIsNull(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
client.subscribeToDesiredProperties(null);
//assert
new Verifications()
{
{
mockedDeviceTwin.subscribeDesiredPropertiesNotification((Map)any);
times = 1;
}
};
}
@Test
public void subscribeToDPSucceedsEvenWhenUserCBIsNull(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final Device mockDevice = new Device()
{
@Override
public void PropertyCall(String propertyKey, Object propertyValue, Object context)
{
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
mockDevice.setDesiredPropertyCallback(new Property("Desired", null), null, null);
//act
client.subscribeToDesiredProperties(mockDevice.getDesiredProp());
//assert
new Verifications()
{
{
mockedDeviceTwin.subscribeDesiredPropertiesNotification((Map)any);
times = 1;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_030: [**If the client has not been open, the function shall throw an IOException.**]**
*/
@Test
public void subscribeToDPThrowsIfCalledWhenClientNotOpen(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB,
@Mocked final Map<Property, Pair<PropertyCallBack<String, Object>, Object>> mockMap) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
returns(true,false);
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
try
{
client.subscribeToDesiredProperties(mockMap);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.subscribeDesiredPropertiesNotification(mockMap);
times = 0;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_029: [**If the client has not started twin before calling this method, the function shall throw an IOException.**]**
*/
@Test
public void subscribeToDPThrowsIfCalledBeforeStartingTwin(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final Map<Property, Pair<PropertyCallBack<String, Object>, Object>> mockMap) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
try
{
client.subscribeToDesiredProperties(mockMap);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.subscribeDesiredPropertiesNotification(mockMap);
times = 0;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_035: [**This method shall send to reported properties by calling updateReportedProperties on the twin object.**]**
*/
@Test
public void sendRPSucceeds(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
client.sendReportedProperties(mockSet);
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet);
times = 1;
}
};
}
@Test
public void sendRPWithVersionSucceeds(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
client.sendReportedProperties(mockSet, 10);
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet, 10);
times = 1;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_032: [**If the client has not started twin before calling this method, the function shall throw an IOException.**]**
*/
@Test
public void sendRPThrowsIfCalledBeforeStartingTwin(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>=";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
try
{
client.sendReportedProperties(mockSet);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet);
times = 0;
}
};
}
@Test
public void sendRPWithVersionThrowsIfCalledBeforeStartingTwin(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
try
{
client.sendReportedProperties(mockSet, 10);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet, 10);
times = 0;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_033: [**If the client has not been open, the function shall throw an IOException.**]**
*/
@Test
public void sendRPThrowsIfCalledWhenClientNotOpen(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>=";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "deviceTwin", mockedDeviceTwin);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
//act
try
{
client.sendReportedProperties(mockSet);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet);
times = 0;
}
};
}
@Test
public void sendRPWithVersionThrowsIfCalledWhenClientNotOpen(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "deviceTwin", mockedDeviceTwin);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
//act
try
{
client.sendReportedProperties(mockSet, 10);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet, 10);
times = 0;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_034: [**If reportedProperties is null or empty, the function shall throw an InvalidParameterException.**]**
*/
@Test
public void sendRPThrowsIfCalledWhenRPNullOrEmpty(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
try
{
client.sendReportedProperties(null);
}
catch (IllegalArgumentException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties((Set)any);
times = 0;
}
};
}
@Test
public void sendRPWithVersionThrowsIfCalledWhenRPNullOrEmpty(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
try
{
client.sendReportedProperties(null, 10);
}
catch (IllegalArgumentException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties((Set)any, 10);
times = 0;
}
};
}
/*
**Codes_SRS_DEVICECLIENT_21_053: [**If version is negative, the function shall throw an IllegalArgumentException.**]**
*/
@Test
public void sendRPThrowsIfCalledWhenVersionIsNegative(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
try
{
client.sendReportedProperties(mockSet, -1);
}
catch (IllegalArgumentException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties((Set)any, -1);
times = 0;
}
};
}
/*
Tests_SRS_DEVICECLIENT_25_038: [**This method shall subscribe to device methods by calling subscribeToDeviceMethod on DeviceMethod object which it created.**]**
*/
@Test
public void subscribeToDeviceMethodSucceeds(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final DeviceMethodCallback mockedDeviceMethodCB,
@Mocked final DeviceMethod mockedMethod) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
final DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.subscribeToDeviceMethod(mockedDeviceMethodCB, null, mockedStatusCB, null);
//assert
new Verifications()
{
{
mockedMethod.subscribeToDeviceMethod(mockedDeviceMethodCB, any);
times = 1;
}
};
}
/*
Tests_SRS_DEVICECLIENT_25_036: [**If the client has not been open, the function shall throw an IOException.**]**
*/
@Test (expected = IOException.class)
public void subscribeToDeviceMethodThrowsIfClientNotOpen(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final DeviceMethodCallback mockedDeviceMethodCB)
throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
}
};
final DeviceClient client = new DeviceClient(connString, protocol);
//act
client.subscribeToDeviceMethod(mockedDeviceMethodCB, null, mockedStatusCB, null);
}
/*
Tests_SRS_DEVICECLIENT_25_037: [**If deviceMethodCallback or deviceMethodStatusCallback is null, the function shall throw an IllegalArgumentException.**]**
*/
@Test (expected = IllegalArgumentException.class)
public void subscribeToDeviceMethodThrowsIfDeviceMethodCallbackNull(@Mocked final IotHubEventCallback mockedStatusCB)
throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
final DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.subscribeToDeviceMethod(null, null, mockedStatusCB, null);
}
@Test (expected = IllegalArgumentException.class)
public void subscribeToDeviceMethodThrowsIfDeviceMethodStatusCallbackNull(@Mocked final DeviceMethodCallback mockedDeviceMethodCB)
throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
final DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.subscribeToDeviceMethod(mockedDeviceMethodCB, null, null, null);
}
/*
Tests_SRS_DEVICECLIENT_25_039: [**This method shall update the deviceMethodCallback if called again, but it shall not subscribe twice.**]**
*/
@Test
public void subscribeToDeviceMethodWorksEvenWhenCalledTwice(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final DeviceMethodCallback mockedDeviceMethodCB,
@Mocked final DeviceMethod mockedMethod) throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
final DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.subscribeToDeviceMethod(mockedDeviceMethodCB, null, mockedStatusCB, null);
// act
client.subscribeToDeviceMethod(mockedDeviceMethodCB, null, mockedStatusCB, null);
// assert
new Verifications()
{
{
mockedMethod.subscribeToDeviceMethod(mockedDeviceMethodCB, any);
times = 2;
}
};
}
// Tests_SRS_DEVICECLIENT_02_015: [If optionName is null or not an option handled by the client, then it shall throw IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void setOptionWithNullOptionNameThrows()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
long someMilliseconds = 4;
// act
client.setOption(null, someMilliseconds);
}
// Tests_SRS_DEVICECLIENT_02_015: [If optionName is null or not an option handled by the client, then it shall throw IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void setOptionWithUnknownOptionNameThrows()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
long someMilliseconds = 4;
// act
client.setOption("thisIsNotAHandledOption", someMilliseconds);
}
//Tests_SRS_DEVICECLIENT_02_017: [Available only for HTTP.]
@Test (expected = IllegalArgumentException.class)
public void setOptionMinimumPollingIntervalWithAMQPfails()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
long someMilliseconds = 4;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.AMQPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setOption("SetMinimumPollingInterval", someMilliseconds);
}
//Tests_SRS_DEVICECLIENT_02_018: [Value needs to have type long].
@Test (expected = IllegalArgumentException.class)
public void setOptionMinimumPollingIntervalWithStringInsteadOfLongFails()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setOption("SetMinimumPollingInterval", "thisIsNotALong");
}
//Tests_SRS_DEVICECLIENT_02_005: [Setting the option can only be done before open call.]
@Test (expected = IllegalStateException.class)
public void setOptionMinimumPollingIntervalAfterOpenFails()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
long value = 3;
// act
client.setOption("SetMinimumPollingInterval", value);
}
//Tests_SRS_DEVICECLIENT_02_016: ["SetMinimumPollingInterval" - time in milliseconds between 2 consecutive polls.]
@Test
public void setOptionMinimumPollingIntervalSucceeds()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
final long value = 3L;
// act
client.setOption("SetMinimumPollingInterval", value);
// assert
new Verifications()
{
{
mockDeviceIO.setReceivePeriodInMilliseconds(value);
}
};
}
// Tests_SRS_DEVICECLIENT_21_040: ["SetSendInterval" - time in milliseconds between 2 consecutive message sends.]
@Test
public void setOptionSendIntervalSucceeds()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
final long value = 3L;
// act
client.setOption("SetSendInterval", value);
// assert
new Verifications()
{
{
mockDeviceIO.setSendPeriodInMilliseconds(value);
}
};
}
@Test (expected = IllegalArgumentException.class)
public void setOptionSendIntervalWithStringInsteadOfLongFails()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setOption("SetSendInterval", "thisIsNotALong");
}
@Test (expected = IllegalArgumentException.class)
public void setOptionValueNullThrows()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setOption("", null);
}
//Tests_SRS_DEVICECLIENT_25_022: [**"SetSASTokenExpiryTime" should have value type long.]
@Test (expected = IllegalArgumentException.class)
public void setOptionSASTokenExpiryTimeWithStringInsteadOfLongFails()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setOption("SetSASTokenExpiryTime", "thisIsNotALong");
}
//Tests_SRS_DEVICECLIENT_25_021: ["SetSASTokenExpiryTime" - time in seconds after which SAS Token expires.]
@Test
public void setOptionSASTokenExpiryTimeHTTPSucceeds()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_25_021: ["SetSASTokenExpiryTime" - time in seconds after which SAS Token expires.]
//Tests_SRS_DEVICECLIENT_25_024: ["SetSASTokenExpiryTime" shall restart the transport if transport is already open after updating expiry time.]
@Test
public void setOptionSASTokenExpiryTimeAfterClientOpenHTTPSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>=";
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 1;
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
Deencapsulation.invoke(mockDeviceIO, "open");
times = 2;
}
};
}
/*Tests_SRS_DEVICECLIENT_25_024: ["SetSASTokenExpiryTime" shall restart the transport
1. If the device currently uses device key and
2. If transport is already open
after updating expiry time.]
*/
@Test
public void setOptionSASTokenExpiryTimeAfterClientOpenTransportWithSasTokenSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessSignature=SharedAccessSignature sr=sample-iothub-hostname.net%2fdevices%2fsample-device-ID&sig=S3%2flPidfBF48B7%2fOFAxMOYH8rpOneq68nu61D%2fBP6fo%3d&se=1469813873";
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 0;
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
Deencapsulation.invoke(mockDeviceIO, "open");
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_25_021: ["SetSASTokenExpiryTime" - Time in secs to specify SAS Token Expiry time.]
@Test
public void setOptionSASTokenExpiryTimeAMQPSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_25_021: ["SetSASTokenExpiryTime" - time in seconds after which SAS Token expires.]
//Tests_SRS_DEVICECLIENT_25_024: ["SetSASTokenExpiryTime" shall restart the transport if transport is already open after updating expiry time.]
@Test
public void setOptionSASTokenExpiryTimeAfterClientOpenAMQPSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 1;
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
Deencapsulation.invoke(mockDeviceIO, "open");
times = 2;
}
};
}
//Tests_SRS_DEVICECLIENT_25_021: [**"SetSASTokenExpiryTime" - Time in secs to specify SAS Token Expiry time.]
@Test
public void setOptionSASTokenExpiryTimeMQTTSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations() {
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
DeviceClient client = new DeviceClient(connString, protocol);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_25_021: ["SetSASTokenExpiryTime" - time in seconds after which SAS Token expires.]
//Tests_SRS_DEVICECLIENT_25_024: ["SetSASTokenExpiryTime" shall restart the transport if transport is already open after updating expiry time.]
@Test
public void setOptionSASTokenExpiryTimeAfterClientOpenMQTTSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations() {
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 1;
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
Deencapsulation.invoke(mockDeviceIO, "open");
times = 2;
}
};
}
// Tests_SRS_DEVICECLIENT_12_025: [If the client configured to use TransportClient the function shall use transport client closeNow() and open() for restart.]
@Test
public void setOptionWithTransportClientSASTokenExpiryTimeAfterClientOpenAMQPSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockTransportClient.closeNow();
times = 1;
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
mockTransportClient.open();
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_027: [The function shall throw IOError if either the deviceIO or the tranportClient's open() or closeNow() throws.]
@Test (expected = IOError.class)
public void setOptionWithTransportClientSASTokenExpiryTimeAfterClientOpenAMQPThrowsTransportClientClose()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockTransportClient.closeNow();
result = new IOException();
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
}
// Tests_SRS_DEVICECLIENT_12_027: [The function shall throw IOError if either the deviceIO or the tranportClient's open() or closeNow() throws.]
@Test (expected = IOError.class)
public void setOptionWithTransportClientSASTokenExpiryTimeAfterClientOpenAMQPThrowsTransportClientOpen()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockTransportClient.open();
result = new IOException();
}
};
final String connString = "HostName=iothub.device.<EMAIL>;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
}
// Tests_SRS_DEVICECLIENT_12_029: [*SetCertificatePath" shall throw if the transportClient or deviceIO already opene.]
@Test (expected = IllegalStateException.class)
public void setOptionWithTransportClientSetCertificatePathTransportOpenedThrows()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// Deencapsulation.setField(client, "config", mockConfig);
// Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final String value = "certificatePath";
// act
client.setOption("SetCertificatePath", value);
}
// Tests_SRS_DEVICECLIENT_12_030: [*SetCertificatePath" shall udate the config on transportClient if tranportClient used.]
@Test
public void setOptionWithTransportClientSetCertificatePathSuccess()
throws IOException, URISyntaxException
{
// arrange
final String value = "certificatePath";
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.CLOSED;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockConfig.getSasTokenAuthentication();
result = mockIotHubSasTokenAuthenticationProvider;
mockIotHubSasTokenAuthenticationProvider.setPathToIotHubTrustedCert(value);
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
// act
client.setOption("SetCertificatePath", value);
new Verifications()
{
{
mockConfig.getAuthenticationType();
times = 1;
mockConfig.getSasTokenAuthentication();
times = 1;
mockIotHubSasTokenAuthenticationProvider.setPathToIotHubTrustedCert(value);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_029: [*SetCertificatePath" shall throw if the transportClient or deviceIO already open, otherwise set the path on the config.]
@Test (expected = IllegalStateException.class)
public void setOptionSetCertificatePathDeviceIOOpenedThrows()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final String value = "certificatePath";
// act
client.setOption("SetCertificatePath", value);
}
// Tests_SRS_DEVICECLIENT_12_030: [*SetCertificatePath" shall udate the config on transportClient if tranportClient used.]
@Test (expected = IllegalArgumentException.class)
public void setOptionSetCertificatePathWrongProtocolThrows()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final String value = "certificatePath";
// act
client.setOption("SetCertificatePath", value);
}
// Tests_SRS_DEVICECLIENT_12_029: [*SetCertificatePath" shall throw if the transportClient or deviceIO already open, otherwise set the path on the config.]
@Test
public void setOptionSetCertificatePathSASSuccess()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.AMQPS_WS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS_WS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final String value = "certificatePath";
// act
client.setOption("SetCertificatePath", value);
new Verifications()
{
{
mockConfig.getAuthenticationType();
times = 1;
mockConfig.getSasTokenAuthentication();
times = 1;
mockIotHubSasTokenAuthenticationProvider.setPathToIotHubTrustedCert(value);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_029: [*SetCertificatePath" shall throw if the transportClient or deviceIO already open, otherwise set the path on the config.]
@Test
public void setOptionSetCertificatePathX509Success()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.AMQPS_WS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.X509_CERTIFICATE;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS_WS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final String value = "certificatePath";
// act
client.setOption("SetCertificatePath", value);
new Verifications()
{
{
mockConfig.getAuthenticationType();
times = 2;
mockConfig.getX509Authentication();
times = 1;
mockIotHubX509AuthenticationProvider.setPathToIotHubTrustedCert(value);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_027: [The function shall throw IOError if either the deviceIO or the tranportClient's open() or closeNow() throws.]
@Test (expected = IOError.class)
public void setOptionClientSASTokenExpiryTimeAfterClientOpenAMQPThrowsDeviceIOClose()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockDeviceIO.close();
result = new IOException();
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
}
// Tests_SRS_DEVICECLIENT_12_027: [The function shall throw IOError if either the deviceIO or the tranportClient's open() or closeNow() throws.]
@Test (expected = IOError.class)
public void setOptionClientSASTokenExpiryTimeAfterClientOpenAMQPThrowsTransportDeviceIOOpen()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
Deencapsulation.invoke(mockDeviceIO, "open");
result = new IOException();
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
}
// Tests_SRS_DEVICECLIENT_12_022: [If the client configured to use TransportClient the SetSendInterval shall throw IOException.]
@Test (expected = IllegalStateException.class)
public void setOptionWithTransportClientThrowsSetSendInterval()
throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
client.setOption("SetSendInterval", "thisIsNotALong");
}
// Tests_SRS_DEVICECLIENT_12_023: [If the client configured to use TransportClient the SetMinimumPollingInterval shall throw IOException.]
@Test (expected = IllegalStateException.class)
public void setOptionWithTransportClientThrowsSetMinimumPollingInterval()
throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
client.setOption("SetMinimumPollingInterval", "thisIsNotALong");
}
//Tests_SRS_DEVICECLIENT_34_055: [If the provided connection string contains an expired SAS token, a SecurityException shall be thrown.]
@Test (expected = SecurityException.class)
public void deviceClientInitializedWithExpiredTokenThrowsSecurityException() throws SecurityException, URISyntaxException
{
//This token will always be expired
final Long expiryTime = 0L;
final String expiredConnString = "HostName=iothub.device.com;DeviceId=2;SharedAccessSignature=SharedAccessSignature sr=hub.azure-devices.net%2Fdevices%2F2&sig=3V1oYPdtyhGPHDDpjS2SnwxoU7CbI%2BYxpLjsecfrtgY%3D&se=" + expiryTime;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
new IotHubConnectionString(anyString);
result = new SecurityException();
mockConfig.getIotHubConnectionString().getSharedAccessToken();
result = expiredConnString;
}
};
// act
DeviceClient client = new DeviceClient(expiredConnString, protocol);
}
//Tests_SRS_DEVICECLIENT_34_044: [**If the SAS token has expired before this call, throw a Security Exception**]
@Test (expected = SecurityException.class)
public void tokenExpiresAfterDeviceClientInitializedBeforeOpen() throws SecurityException, URISyntaxException, IOException
{
final Long expiryTime = Long.MAX_VALUE;
final String connString = "HostName=iothub.device.com;DeviceId=2;SharedAccessSignature=SharedAccessSignature sr=hub.azure-devices.net%2Fdevices%2F2&sig=3V1oYPdtyhGPHDDpjS2SnwxoU7CbI%2BYxpLjsecfrtgY%3D&se=" + expiryTime;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
new NonStrictExpectations()
{
{
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockConfig.getSasTokenAuthentication().isRenewalNecessary();
result = true;
mockConfig.getIotHubConnectionString().getSharedAccessToken();
result = "SharedAccessSignature sr=hub.azure-devices.net%2Fdevices%2F2&sig=3V1oYPdtyhGPHDDpjS2SnwxoU7CbI%2BYxpLjsecfrtgY%3D&se=" + expiryTime;
}
};
// act
client.open();
}
/* Tests_SRS_DEVICECLIENT_21_044: [The uploadToBlobAsync shall asynchronously upload the stream in `inputStream` to the blob in `destinationBlobName`.] */
/* Tests_SRS_DEVICECLIENT_21_048: [If there is no instance of the FileUpload, the uploadToBlobAsync shall create a new instance of the FileUpload.] */
/* Tests_SRS_DEVICECLIENT_21_050: [The uploadToBlobAsync shall start the stream upload process, by calling uploadToBlobAsync on the FileUpload class.] */
@Test
public void startFileUploadSucceeds(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
result = mockedFileUpload;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
// assert
new Verifications()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
times = 1;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_054: [If the fileUpload is not null, the closeNow shall call closeNow on fileUpload.] */
@Test
public void closeNowClosesFileUploadSucceeds(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
result = mockedFileUpload;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
// act
client.closeNow();
// assert
new Verifications()
{
{
Deencapsulation.invoke(mockedFileUpload, "closeNow");
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_045: [If the `callback` is null, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadNullCallbackThrows(@Mocked final InputStream mockInputStream,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, null, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_046: [If the `inputStream` is null, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadNullInputStreamThrows(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, (InputStream) null, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_052: [If the `streamLength` is negative, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadNegativeLengthThrows(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final InputStream mockInputStream,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, -1, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_047: [If the `destinationBlobName` is null, empty, or not valid, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadNullBlobNameThrows(@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(null, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_047: [If the `destinationBlobName` is null, empty, or not valid, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadEmptyBlobNameThrows(@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync("", mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_047: [If the `destinationBlobName` is null, empty, or not valid, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadInvalidUTF8BlobNameThrows(@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid\u1234/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_047: [If the `destinationBlobName` is null, empty, or not valid, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadInvalidBigBlobNameThrows(@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
StringBuilder bigBlobName = new StringBuilder();
String directory = "directory/";
final long streamLength = 100;
// create a blob name bigger than 1024 characters.
for (int i = 0; i < (2000/directory.length()); i++)
{
bigBlobName.append(directory);
}
bigBlobName.append("image.jpg");
final String destinationBlobName = bigBlobName.toString();
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_047: [If the `destinationBlobName` is null, empty, or not valid, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadInvalidPathBlobNameThrows(@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
StringBuilder bigBlobName = new StringBuilder();
String directory = "a/";
final long streamLength = 100;
// create a blob name with more than 254 path segments.
for (int i = 0; i < 300; i++)
{
bigBlobName.append(directory);
}
bigBlobName.append("image.jpg");
final String destinationBlobName = bigBlobName.toString();
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_048: [If there is no instance of the FileUpload, the uploadToBlobAsync shall create a new instance of the FileUpload.] */
@Test
public void startFileUploadOneFileUploadInstanceSucceeds(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
result = mockedFileUpload;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
// assert
new Verifications()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
times = 1;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
times = 2;
}
};
}
//Tests_SRS_DEVICECLIENT_99_001: [The registerConnectionStateCallback shall register the callback with the Device IO.]
//Tests_SRS_DEVICECLIENT_99_002: [The registerConnectionStateCallback shall register the callback even if the client is not open.]
@Test
public void registerConnectionStateCallback(@Mocked final IotHubConnectionStateCallback mockedStateCB) throws URISyntaxException, IOException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.registerConnectionStateCallback(mockedStateCB, null);
//assert
new Verifications()
{
{
mockDeviceIO.registerConnectionStateCallback(mockedStateCB, null);
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_99_003: [If the callback is null the method shall throw an IllegalArgument exception.]
@Test (expected = IllegalArgumentException.class)
public void registerConnectionStateCallbackNullCallback()
throws IllegalArgumentException, URISyntaxException, IOException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final DeviceClient client = new DeviceClient(connString, protocol);
//act
client.registerConnectionStateCallback(null, null);
}
/* Tests_SRS_DEVICECLIENT_21_049: [If uploadToBlobAsync failed to create a new instance of the FileUpload, it shall bypass the exception.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadNewInstanceThrows(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
result = new IllegalArgumentException();
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
// Tests_SRS_DEVICECLIENT_34_066: [If this function is called when the device client is using x509 authentication, an UnsupportedOperationException shall be thrown.]
@Test (expected = UnsupportedOperationException.class)
public void startFileUploadUploadToBlobAsyncAuthTypeThrows(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.X509_CERTIFICATE;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_051: [If uploadToBlobAsync failed to start the upload using the FileUpload, it shall bypass the exception.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadUploadToBlobAsyncThrows(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
result = mockedFileUpload;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
result = new IllegalArgumentException();
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
//Tests_SRS_DEVICECLIENT_34_065: [""SetSASTokenExpiryTime" if this option is called when not using sas token authentication, an IllegalStateException shall be thrown.*]
@Test (expected = IllegalStateException.class)
public void setOptionSASTokenExpiryTimeWhenNotUsingSasTokenAuthThrows() throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.X509_CERTIFICATE;
}
};
DeviceClient client = new DeviceClient(connString, protocol, "someCert", false, "someKey", false);
// act
client.setOption("SetSASTokenExpiryTime", 25L);
}
// Tests_SRS_DEVICECLIENT_12_002: [The function shall return with he current value of client config.]
@Test
public void getConfig() throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;" + "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "config", mockConfig);
// act
DeviceClientConfig deviceClientConfig = Deencapsulation.invoke(client, "getConfig");
// assert
assertEquals(deviceClientConfig, mockConfig);
}
// Tests_SRS_DEVICECLIENT_12_003: [The function shall return with he current value of the client's underlying DeviceIO.]
@Test
public void getGetDeviceIO() throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;" + "SharedAccessKey=<KEY>=";
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.invoke(client, "setDeviceIO", mockDeviceIO);
// act
DeviceIO deviceIO = Deencapsulation.invoke(client, "getDeviceIO");
// assert
assertEquals(deviceIO, mockDeviceIO);
}
// Tests_SRS_DEVICECLIENT_12_004: [The function shall set the client's underlying DeviceIO to the value of the given deviceIO parameter.]
@Test
public void setGetDeviceIO() throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;" + "SharedAccessKey=<KEY>=";
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
Deencapsulation.invoke(client, "setDeviceIO", mockDeviceIO);
// assert
DeviceIO deviceIO = Deencapsulation.getField(client, "deviceIO");
assertEquals(deviceIO, mockDeviceIO);
}
// Tests_SRS_DEVICECLIENT_12_028: [The constructor shall shall set the config, deviceIO and tranportClient to null.]
@Test
public void unusedConstructor()
{
// act
DeviceClient client = Deencapsulation.newInstance(DeviceClient.class);
// assert
assertNull(Deencapsulation.getField(client, "config"));
assertNull(Deencapsulation.getField(client, "deviceIO"));
}
//Tests_SRS_DEVICECLIENT_34_068: [If the callback is null the method shall throw an IllegalArgument exception.]
@Test (expected = IllegalArgumentException.class)
public void registerConnectionStatusChangeCallbackThrowsForNullCallback() throws URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=adjkl234j52=;";
DeviceClient client = new DeviceClient(connString, IotHubClientProtocol.AMQPS);
//act
client.registerConnectionStatusChangeCallback(null, new Object());
}
//Tests_SRS_DEVICECLIENT_34_069: [This function shall register the provided callback and context with its device IO instance.]
@Test
public void registerConnectionStatusChangeCallbackRegistersCallbackWithDeviceIO() throws URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>=;";
DeviceClient client = new DeviceClient(connString, IotHubClientProtocol.AMQPS);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final Object context = new Object();
//act
client.registerConnectionStatusChangeCallback(mockedIotHubConnectionStatusChangeCallback, context);
//assert
new Verifications()
{
{
mockDeviceIO.registerConnectionStatusChangeCallback(mockedIotHubConnectionStatusChangeCallback, context);
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_28_001: [The function shall set the device config's RetryPolicy .]
@Test
public void setRetryPolicySetPolicy() throws URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>=";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
//act
client.setRetryPolicy(new ExponentialBackoffWithJitter());
//assert
new Verifications()
{
{
mockConfig.setRetryPolicy((RetryPolicy) any);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_34_070: [The function shall set the device config's operation timeout .]
@Test
public void setDeviceOperationTimeoutSetsConfig() throws URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
final long expectedTimeout = 1034;
Deencapsulation.setField(client, "config", mockConfig);
//act
client.setOperationTimeout(expectedTimeout);
//assert
new Verifications()
{
{
Deencapsulation.invoke(mockConfig, "setOperationTimeout", expectedTimeout);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_34_071: [This function shall return the product info saved in config.]
@Test
public void getProductInfoFetchesFromConfig() throws URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
new StrictExpectations()
{
{
mockConfig.getProductInfo();
result = mockedProductInfo;
}
};
//act
ProductInfo productInfo = client.getProductInfo();
//assert
assertEquals(mockedProductInfo, productInfo);
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package tests.unit.com.microsoft.azure.sdk.iot.device;
import com.microsoft.azure.sdk.iot.device.*;
import com.microsoft.azure.sdk.iot.device.DeviceTwin.*;
import com.microsoft.azure.sdk.iot.device.auth.IotHubSasTokenAuthenticationProvider;
import com.microsoft.azure.sdk.iot.device.auth.IotHubX509AuthenticationProvider;
import com.microsoft.azure.sdk.iot.device.exceptions.TransportException;
import com.microsoft.azure.sdk.iot.device.fileupload.FileUpload;
import com.microsoft.azure.sdk.iot.device.transport.ExponentialBackoffWithJitter;
import com.microsoft.azure.sdk.iot.device.transport.RetryPolicy;
import com.microsoft.azure.sdk.iot.device.transport.amqps.IoTHubConnectionType;
import com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider;
import com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException;
import mockit.*;
import org.junit.Test;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Unit tests for DeviceClient.
* Methods: 100%
* Lines: 96%
*/
public class DeviceClientTest
{
@Mocked
DeviceClientConfig mockConfig;
@Mocked
IotHubConnectionString mockIotHubConnectionString;
@Mocked
DeviceIO mockDeviceIO;
@Mocked
TransportClient mockTransportClient;
@Mocked
FileUpload mockFileUpload;
@Mocked
IotHubSasTokenAuthenticationProvider mockIotHubSasTokenAuthenticationProvider;
@Mocked
IotHubX509AuthenticationProvider mockIotHubX509AuthenticationProvider;
@Mocked
SecurityProvider mockSecurityProvider;
@Mocked
IotHubConnectionStatusChangeCallback mockedIotHubConnectionStatusChangeCallback;
@Mocked
ProductInfo mockedProductInfo;
private static long SEND_PERIOD_MILLIS = 10L;
private static long RECEIVE_PERIOD_MILLIS_AMQPS = 10L;
private static long RECEIVE_PERIOD_MILLIS_HTTPS = 25*60*1000; /*25 minutes*/
private void deviceClientInstanceExpectation(final String connectionString, final IotHubClientProtocol protocol)
{
final long receivePeriod;
switch (protocol)
{
case HTTPS:
receivePeriod = RECEIVE_PERIOD_MILLIS_HTTPS;
break;
default:
receivePeriod = RECEIVE_PERIOD_MILLIS_AMQPS;
break;
}
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(IotHubConnectionString.class, connectionString);
result = mockIotHubConnectionString;
Deencapsulation.newInstance(DeviceClientConfig.class, mockIotHubConnectionString, DeviceClientConfig.AuthType.SAS_TOKEN);
result = mockConfig;
Deencapsulation.newInstance(DeviceIO.class,
mockConfig, SEND_PERIOD_MILLIS, receivePeriod);
result = mockDeviceIO;
}
};
}
// Tests_SRS_DEVICECLIENT_12_009: [The constructor shall interpret the connection string as a set of key-value pairs delimited by ';', using the object IotHubConnectionString.]
// Tests_SRS_DEVICECLIENT_12_010: [The constructor shall set the connection type to USE_TRANSPORTCLIENT.]
// Tests_SRS_DEVICECLIENT_12_011: [The constructor shall set the deviceIO to null.]
// Tests_SRS_DEVICECLIENT_12_016: [The constructor shall save the transportClient parameter.]
// Tests_SRS_DEVICECLIENT_12_017: [The constructor shall register the device client with the transport client.]
@Test
public void constructorTransportClientSuccess() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>;";
// act
final DeviceClient client = new DeviceClient(connString, mockTransportClient);
// assert
new Verifications()
{
{
IotHubConnectionString iotHubConnectionString = Deencapsulation.newInstance(IotHubConnectionString.class, connString);
times = 1;
Deencapsulation.newInstance(DeviceClientConfig.class, iotHubConnectionString, DeviceClientConfig.AuthType.SAS_TOKEN);
times = 1;
IoTHubConnectionType ioTHubConnectionType = Deencapsulation.getField(client, "ioTHubConnectionType");
assertEquals(IoTHubConnectionType.USE_TRANSPORTCLIENT, ioTHubConnectionType);
DeviceIO deviceIO = Deencapsulation.getField(client, "deviceIO");
assertNull(deviceIO);
TransportClient actualTransportClient = Deencapsulation.getField(client, "transportClient");
assertEquals(mockTransportClient, actualTransportClient);
Deencapsulation.invoke(mockTransportClient, "registerDeviceClient", client);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_008: [If the connection string is null or empty, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void constructorTransportClientNullConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = null;
// act
new DeviceClient(connString, mockTransportClient);
}
// Tests_SRS_DEVICECLIENT_12_008: [If the connection string is null or empty, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void constructorTransportClientEmptyConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = "";
// act
new DeviceClient(connString, mockTransportClient);
}
// Tests_SRS_DEVICECLIENT_12_018: [If the tranportClient is null, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void constructorTransportClientTransportClientNullThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>;";
// act
new DeviceClient(connString, (TransportClient) null);
}
/* Tests_SRS_DEVICECLIENT_21_001: [The constructor shall interpret the connection string as a set of key-value pairs delimited by ';', using the object IotHubConnectionString.] */
/* Tests_SRS_DEVICECLIENT_21_002: [The constructor shall initialize the IoT Hub transport for the protocol specified, creating a instance of the deviceIO.] */
/* Tests_SRS_DEVICECLIENT_21_003: [The constructor shall save the connection configuration using the object DeviceClientConfig.] */
@Test
public void constructorSuccess() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>=;";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
final DeviceClient client = new DeviceClient(connString, protocol);
// assert
new Verifications()
{
{
IotHubConnectionString iotHubConnectionString = Deencapsulation.newInstance(IotHubConnectionString.class, connString);
times = 1;
Deencapsulation.newInstance(DeviceClientConfig.class, iotHubConnectionString, DeviceClientConfig.AuthType.SAS_TOKEN);
times = 1;
// Tests_SRS_DEVICECLIENT_12_012: [The constructor shall set the connection type to SINGLE_CLIENT.]
IoTHubConnectionType ioTHubConnectionType = Deencapsulation.getField(client, "ioTHubConnectionType");
assertEquals(IoTHubConnectionType.SINGLE_CLIENT, ioTHubConnectionType);
// Tests_SRS_DEVICECLIENT_12_015: [The constructor shall set the transportClient to null.]
TransportClient transportClient = Deencapsulation.getField(client, "transportClient");
assertNull(transportClient);
}
};
}
//Tests_SRS_DEVICECLIENT_34_058: [The constructor shall interpret the connection string as a set of key-value pairs delimited by ';', using the object IotHubConnectionString.]
//Tests_SRS_DEVICECLIENT_34_059: [The constructor shall initialize the IoT Hub transport for the protocol specified, creating a instance of the deviceIO.]
//Tests_SRS_DEVICECLIENT_34_060: [The constructor shall save the connection configuration using the object DeviceClientConfig.]
//Tests_SRS_DEVICECLIENT_34_063: [This function shall save the provided certificate and key within its config.]
@Test
public void constructorSuccessX509() throws URISyntaxException, IOException
{
// arrange
final String publicKeyCert = "someCert";
final String privateKey = "someKey";
final String connString =
"HostName=iothub.device.com;DeviceId=testdevice;x509=true";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS_WS;
new NonStrictExpectations()
{
{
mockIotHubConnectionString.isUsingX509();
result = true;
}
};
// act
final DeviceClient client = new DeviceClient(connString, protocol, publicKeyCert, false, privateKey, false);
// assert
new Verifications()
{
{
Deencapsulation.newInstance(IotHubConnectionString.class, connString);
times = 1;
new DeviceClientConfig((IotHubConnectionString) any, publicKeyCert, false, privateKey, false);
times = 1;
// Tests_SRS_DEVICECLIENT_12_013: [The constructor shall set the connection type to SINGLE_CLIENT.]
IoTHubConnectionType ioTHubConnectionType = Deencapsulation.getField(client, "ioTHubConnectionType");
assertEquals(IoTHubConnectionType.SINGLE_CLIENT, ioTHubConnectionType);
// Tests_SRS_DEVICECLIENT_12_014: [The constructor shall set the transportClient to null.]
TransportClient transportClient = Deencapsulation.getField(client, "transportClient");
assertNull(transportClient);
}
};
}
/* Tests_SRS_DEVICECLIENT_21_004: [If the connection string is null or empty, the function shall throw an IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void constructorNullConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = null;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol);
}
//Tests_SRS_DEVICECLIENT_34_061: [If the connection string is null or empty, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void x509ConstructorNullConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = null;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol, "any cert", false, "any key", false);
}
//Tests_SRS_DEVICECLIENT_34_064: [If the provided protocol is null, this function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void createFromSecurityProviderThrowsForNullProtocol() throws URISyntaxException, SecurityProviderException, IOException
{
//act
DeviceClient.createFromSecurityProvider("some uri", "some device id", mockSecurityProvider, null);
}
//Tests_SRS_DEVICECLIENT_34_065: [The provided uri and device id will be used to create an iotHubConnectionString that will be saved in config.]
//Tests_SRS_DEVICECLIENT_34_066: [The provided security provider will be saved in config.]
//Tests_SRS_DEVICECLIENT_34_067: [The constructor shall initialize the IoT Hub transport for the protocol specified, creating a instance of the deviceIO.]
@Test
public void createFromSecurityProviderUsesUriAndDeviceIdAndSavesSecurityProviderAndCreatesDeviceIO() throws URISyntaxException, SecurityProviderException, IOException
{
//arrange
final String expectedUri = "some uri";
final String expectedDeviceId = "some device id";
final IotHubClientProtocol expectedProtocol = IotHubClientProtocol.HTTPS;
new StrictExpectations()
{
{
new IotHubConnectionString(expectedUri, expectedDeviceId, null, null);
result = mockIotHubConnectionString;
}
};
//act
DeviceClient.createFromSecurityProvider(expectedUri, expectedDeviceId, mockSecurityProvider, expectedProtocol);
//assert
new Verifications()
{
{
Deencapsulation.newInstance(DeviceClientConfig.class, new Class[] {IotHubConnectionString.class, SecurityProvider.class}, mockIotHubConnectionString, mockSecurityProvider);
times = 1;
Deencapsulation.newInstance("com.microsoft.azure.sdk.iot.device.DeviceIO",
new Class[] {DeviceClientConfig.class, long.class, long.class},
any, SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_HTTPS);
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_004: [If the connection string is null or empty, the function shall throw an IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void constructorEmptyConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = "";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol);
}
//Tests_SRS_DEVICECLIENT_34_062: [If protocol is null, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void x509ConstructorEmptyConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString = "";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol, "any cert", false, "any key", false);
}
/* Tests_SRS_DEVICECLIENT_21_005: [If protocol is null, the function shall throw an IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void constructorNullProtocolThrows() throws URISyntaxException, IOException
{
// arrange
final String connString =
"HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>=;";
final IotHubClientProtocol protocol = null;
// act
new DeviceClient(connString, protocol);
}
/* Tests_SRS_DEVICECLIENT_21_001: [The constructor shall interpret the connection string as a set of key-value pairs delimited by ';', using the object IotHubConnectionString.] */
@Test
public void constructorBadConnectionStringThrows() throws URISyntaxException, IOException
{
// arrange
final String connString =
"HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>;";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(IotHubConnectionString.class, connString);
result = new IllegalArgumentException();
}
};
// act
try
{
new DeviceClient(connString, protocol);
}
catch (IllegalArgumentException expected)
{
// Don't do anything, throw expected.
}
// assert
new Verifications()
{
{
IotHubConnectionString iotHubConnectionString = Deencapsulation.newInstance(IotHubConnectionString.class, connString);
times = 1;
Deencapsulation.newInstance(DeviceClientConfig.class, iotHubConnectionString, DeviceClientConfig.AuthType.SAS_TOKEN);
times = 0;
Deencapsulation.newInstance("com.microsoft.azure.sdk.iot.device.DeviceIO",
new Class[] {DeviceClientConfig.class, long.class, long.class},
any, SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_AMQPS);
times = 0;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_002: [The constructor shall initialize the IoT Hub transport for the protocol specified, creating a instance of the deviceIO.] */
@Test (expected = IllegalArgumentException.class)
public void constructorBadDeviceIOThrows() throws URISyntaxException, IOException
{
// arrange
final String connString =
"HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>;";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol);
// assert
new Verifications()
{
{
Deencapsulation.newInstance(IotHubConnectionString.class, connString);
times = 1;
Deencapsulation.newInstance(DeviceClientConfig.class, (IotHubConnectionString)any, DeviceClientConfig.AuthType.SAS_TOKEN);
times = 1;
Deencapsulation.newInstance("com.microsoft.azure.sdk.iot.device.DeviceIO",
new Class[] {DeviceClientConfig.class, IotHubClientProtocol.class, long.class, long.class},
(DeviceClientConfig)any, protocol, SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_AMQPS);
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_003: [The constructor shall save the connection configuration using the object DeviceClientConfig.] */
@Test (expected = IllegalArgumentException.class)
public void constructorBadDeviceClientConfigThrows() throws URISyntaxException, IOException
{
// arrange
final String connString =
"HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>;";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
// act
new DeviceClient(connString, protocol);
// assert
new Verifications()
{
{
Deencapsulation.newInstance(DeviceClientConfig.class, (IotHubConnectionString)any, DeviceClientConfig.AuthType.SAS_TOKEN);
times = 1;
Deencapsulation.newInstance("com.microsoft.azure.sdk.iot.device.DeviceIO",
new Class[] {DeviceClientConfig.class, IotHubClientProtocol.class, long.class, long.class},
(DeviceClientConfig)any, protocol, SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_AMQPS);
times = 0;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_006: [The open shall open the deviceIO connection.] */
@Test
public void openOpensDeviceIOSuccess() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.open();
// assert
new Verifications()
{
{
Deencapsulation.newInstance("com.microsoft.azure.sdk.iot.device.DeviceIO",
new Class[] {DeviceClientConfig.class, long.class, long.class},
any, SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_AMQPS);
times = 1;
Deencapsulation.invoke(mockDeviceIO, "open");
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_007: [If the client has been initialized to use TransportClient and the TransportClient is not opened yet the function shall throw an IOException.]
@Test (expected = IOException.class)
public void openUseTransportClientAndCalledBeforeTransportClientOpenedThrows() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.CLOSED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
client.open();
}
// Tests_SRS_DEVICECLIENT_12_019: [If the client has been initialized to use TransportClient and the TransportClient is already opened the function shall do nothing.]
@Test
public void openUseTransportClientAndCalledAfterTransportClientOpenedDoNothing() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
// act
client.open();
new Verifications()
{
{
Deencapsulation.invoke(mockDeviceIO, "open");
times = 0;
}
};
}
/* Tests_SRS_DEVICECLIENT_11_040: [The function shall finish all ongoing tasks.] */
/* Tests_SRS_DEVICECLIENT_11_041: [The function shall cancel all recurring tasks.] */
/* Tests_SRS_DEVICECLIENT_21_042: [The closeNow shall closeNow the deviceIO connection.] */
/* Tests_SRS_DEVICECLIENT_21_043: [If the closing a connection via deviceIO is not successful, the closeNow shall throw IOException.] */
@Test
public void closeClosesTransportSuccess() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
new NonStrictExpectations()
{
{
mockDeviceIO.isEmpty();
result = true;
}
};
// act
client.close();
// assert
new Verifications()
{
{
mockDeviceIO.isEmpty();
times = 1;
mockDeviceIO.close();
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_11_040: [The function shall finish all ongoing tasks.] */
/* Tests_SRS_DEVICECLIENT_11_041: [The function shall cancel all recurring tasks.] */
/* Tests_SRS_DEVICECLIENT_21_042: [The closeNow shall closeNow the deviceIO connection.] */
/* Tests_SRS_DEVICECLIENT_21_043: [If the closing a connection via deviceIO is not successful, the closeNow shall throw IOException.] */
@Test
public void closeWaitAndClosesTransportSuccess() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
new NonStrictExpectations()
{
{
mockDeviceIO.isEmpty();
returns(false, false, true);
}
};
// act
client.close();
// assert
new Verifications()
{
{
mockDeviceIO.isEmpty();
times = 3;
mockDeviceIO.close();
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_006: [If the client has been initialized to use TransportClient and the TransportClient is already opened the function shall throw an IOException.]
@Test (expected = IOException.class)
public void closeUseTransportClientAndCalledAfterTransportClientOpenedThrows() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
client.close();
}
// Tests_SRS_DEVICECLIENT_12_020: [If the client has been initialized to use TransportClient and the TransportClient is not opened yet the function shall do nothing.]
@Test
public void closeUseTransportClientAndCalledBeforeTransportClientOpenedDoNothing() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.CLOSED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
// act
client.close();
new Verifications()
{
{
mockDeviceIO.isEmpty();
times = 0;
mockDeviceIO.close();
times = 0;
}
};
}
// Tests_SRS_DEVICECLIENT_12_005: [If the client has been initialized to use TransportClient and the TransportClient is already opened the function shall throw an IOException.]
@Test (expected = IOException.class)
public void closeNowUseTransportClientAndCalledAfterTransportClientOpenedThrows() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
client.closeNow();
}
// Tests_SRS_DEVICECLIENT_12_021: [If the client has been initialized to use TransportClient and the TransportClient is not opened yet the function shall do nothing.]
@Test
public void closeNowUseTransportClientAndCalledBeforeTransportClientOpenedDoNothing() throws URISyntaxException, IOException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.CLOSED;
}
};
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
Deencapsulation.setField(client, "fileUpload", mockFileUpload);
// act
client.closeNow();
new Verifications()
{
{
mockFileUpload.closeNow();
times = 0;
mockDeviceIO.close();
times = 0;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_008: [The closeNow shall closeNow the deviceIO connection.] */
@Test
public void closeNowClosesTransportSuccess() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
// act
client.closeNow();
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_009: [If the closing a connection via deviceIO is not successful, the closeNow shall throw IOException.] */
@Test
public void closeNowBadCloseTransportThrows() throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.close();
result = new IOException();
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
// act
try
{
client.closeNow();
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_010: [The sendEventAsync shall asynchronously send the message using the deviceIO connection.] */
@Test
public void sendEventAsyncSendsSuccess(
@Mocked final Message mockMessage,
@Mocked final IotHubEventCallback mockCallback)
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final Map<String, Object> context = new HashMap<>();
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
client.open();
// act
client.sendEventAsync(mockMessage, mockCallback, context);
// assert
new Verifications()
{
{
mockDeviceIO.sendEventAsync(mockMessage, mockCallback, context, mockConfig.getIotHubConnectionString());
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_011: [If starting to send via deviceIO is not successful, the sendEventAsync shall bypass the threw exception.] */
// Tests_SRS_DEVICECLIENT_12_001: [The function shall call deviceIO.sendEventAsync with the client's config parameter to enable multiplexing.]
@Test
public void sendEventAsyncBadSendThrows(
@Mocked final Message mockMessage,
@Mocked final IotHubEventCallback mockCallback)
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final Map<String, Object> context = new HashMap<>();
new NonStrictExpectations()
{
{
mockDeviceIO.sendEventAsync(mockMessage, mockCallback, context, null);
result = new IllegalStateException();
}
};
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
client.open();
// act
try
{
client.sendEventAsync(mockMessage, mockCallback, context);
}
catch (IllegalStateException expected)
{
// Don't do anything, throw expected.
}
// assert
new Verifications()
{
{
mockDeviceIO.sendEventAsync(mockMessage, mockCallback, context, mockConfig.getIotHubConnectionString());
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_11_013: [The function shall set the message callback, with its associated context.]
// Tests_SRS_DEVICECLIENT_12_001: [The function shall call deviceIO.sendEventAsync with the client's config parameter to enable multiplexing.]
@Test
public void setMessageCallbackSetsMessageCallback(
@Mocked final MessageCallback mockCallback)
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>=";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final Map<String, Object> context = new HashMap<>();
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setMessageCallback(mockCallback, context);
// assert
new Verifications()
{
{
mockConfig.setMessageCallback(mockCallback, context);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_11_014: [If the callback is null but the context is non-null, the function shall throw an IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void setMessageCallbackRejectsNullCallbackAndNonnullContext()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final Map<String, Object> context = new HashMap<>();
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setMessageCallback(null, context);
}
/*
**Tests_SRS_DEVICECLIENT_25_025: [**The function shall create a new instance of class Device Twin and request all twin properties by calling getDeviceTwin**]**
*/
@Test
public void startDeviceTwinSucceeds(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//assert
new Verifications()
{
{
mockedDeviceTwin.getDeviceTwin();
times = 1;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_026: [**If the deviceTwinStatusCallback or genericPropertyCallBack is null, the function shall throw an InvalidParameterException.**]**
*/
@Test (expected = IllegalArgumentException.class)
public void startDeviceTwinThrowsIfStatusCBisNull(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.startDeviceTwin(null, null, mockedPropertyCB, null);
//assert
new Verifications()
{
{
mockedDeviceTwin.getDeviceTwin();
times = 0;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_026: [**If the deviceTwinStatusCallback or genericPropertyCallBack is null, the function shall throw an InvalidParameterException.**]**
*/
@Test (expected = IllegalArgumentException.class)
public void startDeviceTwinThrowsIfPropCBisNull(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.startDeviceTwin(mockedStatusCB, null, (PropertyCallBack) null, null);
}
/*
**Tests_SRS_DEVICECLIENT_25_028: [**If this method is called twice on the same instance of the client then this method shall throw UnsupportedOperationException.**]**
*/
@Test
public void startDeviceTwinThrowsIfCalledTwice(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
try
{
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
}
catch (UnsupportedOperationException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.getDeviceTwin();
times = 1;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_027: [**If the client has not been open, the function shall throw an IOException.**]**
*/
@Test (expected = IOException.class)
public void startDeviceTwinThrowsIfCalledWhenClientNotOpen(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
//act
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
}
/*
**Tests_SRS_DEVICECLIENT_25_031: [**This method shall subscribe to desired properties by calling subscribeDesiredPropertiesNotification on the twin object.**]**
*/
@Test
public void subscribeToDPSucceeds(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB,
@Mocked final Map<Property, Pair<PropertyCallBack<String, Object>, Object>> mockMap) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
client.subscribeToDesiredProperties(mockMap);
//assert
new Verifications()
{
{
mockedDeviceTwin.subscribeDesiredPropertiesNotification(mockMap);
times = 1;
}
};
}
@Test
public void subscribeToDPWorksWhenMapIsNull(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
client.subscribeToDesiredProperties(null);
//assert
new Verifications()
{
{
mockedDeviceTwin.subscribeDesiredPropertiesNotification((Map)any);
times = 1;
}
};
}
@Test
public void subscribeToDPSucceedsEvenWhenUserCBIsNull(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final Device mockDevice = new Device()
{
@Override
public void PropertyCall(String propertyKey, Object propertyValue, Object context)
{
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
mockDevice.setDesiredPropertyCallback(new Property("Desired", null), null, null);
//act
client.subscribeToDesiredProperties(mockDevice.getDesiredProp());
//assert
new Verifications()
{
{
mockedDeviceTwin.subscribeDesiredPropertiesNotification((Map)any);
times = 1;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_030: [**If the client has not been open, the function shall throw an IOException.**]**
*/
@Test
public void subscribeToDPThrowsIfCalledWhenClientNotOpen(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB,
@Mocked final Map<Property, Pair<PropertyCallBack<String, Object>, Object>> mockMap) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
returns(true,false);
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
try
{
client.subscribeToDesiredProperties(mockMap);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.subscribeDesiredPropertiesNotification(mockMap);
times = 0;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_029: [**If the client has not started twin before calling this method, the function shall throw an IOException.**]**
*/
@Test
public void subscribeToDPThrowsIfCalledBeforeStartingTwin(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final Map<Property, Pair<PropertyCallBack<String, Object>, Object>> mockMap) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
try
{
client.subscribeToDesiredProperties(mockMap);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.subscribeDesiredPropertiesNotification(mockMap);
times = 0;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_035: [**This method shall send to reported properties by calling updateReportedProperties on the twin object.**]**
*/
@Test
public void sendRPSucceeds(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
client.sendReportedProperties(mockSet);
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet);
times = 1;
}
};
}
@Test
public void sendRPWithVersionSucceeds(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
client.sendReportedProperties(mockSet, 10);
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet, 10);
times = 1;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_032: [**If the client has not started twin before calling this method, the function shall throw an IOException.**]**
*/
@Test
public void sendRPThrowsIfCalledBeforeStartingTwin(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>=";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
try
{
client.sendReportedProperties(mockSet);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet);
times = 0;
}
};
}
@Test
public void sendRPWithVersionThrowsIfCalledBeforeStartingTwin(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
try
{
client.sendReportedProperties(mockSet, 10);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet, 10);
times = 0;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_033: [**If the client has not been open, the function shall throw an IOException.**]**
*/
@Test
public void sendRPThrowsIfCalledWhenClientNotOpen(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>=";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "deviceTwin", mockedDeviceTwin);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
//act
try
{
client.sendReportedProperties(mockSet);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet);
times = 0;
}
};
}
@Test
public void sendRPWithVersionThrowsIfCalledWhenClientNotOpen(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "deviceTwin", mockedDeviceTwin);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
//act
try
{
client.sendReportedProperties(mockSet, 10);
}
catch (IOException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties(mockSet, 10);
times = 0;
}
};
}
/*
**Tests_SRS_DEVICECLIENT_25_034: [**If reportedProperties is null or empty, the function shall throw an InvalidParameterException.**]**
*/
@Test
public void sendRPThrowsIfCalledWhenRPNullOrEmpty(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
try
{
client.sendReportedProperties(null);
}
catch (IllegalArgumentException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties((Set)any);
times = 0;
}
};
}
@Test
public void sendRPWithVersionThrowsIfCalledWhenRPNullOrEmpty(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
try
{
client.sendReportedProperties(null, 10);
}
catch (IllegalArgumentException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties((Set)any, 10);
times = 0;
}
};
}
/*
**Codes_SRS_DEVICECLIENT_21_053: [**If version is negative, the function shall throw an IllegalArgumentException.**]**
*/
@Test
public void sendRPThrowsIfCalledWhenVersionIsNegative(@Mocked final DeviceTwin mockedDeviceTwin,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB,
@Mocked final Set<Property> mockSet) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.startDeviceTwin(mockedStatusCB, null, mockedPropertyCB, null);
//act
try
{
client.sendReportedProperties(mockSet, -1);
}
catch (IllegalArgumentException expected)
{
// Don't do anything, throw expected.
}
//assert
new Verifications()
{
{
mockedDeviceTwin.updateReportedProperties((Set)any, -1);
times = 0;
}
};
}
/*
Tests_SRS_DEVICECLIENT_25_038: [**This method shall subscribe to device methods by calling subscribeToDeviceMethod on DeviceMethod object which it created.**]**
*/
@Test
public void subscribeToDeviceMethodSucceeds(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final DeviceMethodCallback mockedDeviceMethodCB,
@Mocked final DeviceMethod mockedMethod) throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
final DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.subscribeToDeviceMethod(mockedDeviceMethodCB, null, mockedStatusCB, null);
//assert
new Verifications()
{
{
mockedMethod.subscribeToDeviceMethod(mockedDeviceMethodCB, any);
times = 1;
}
};
}
/*
Tests_SRS_DEVICECLIENT_25_036: [**If the client has not been open, the function shall throw an IOException.**]**
*/
@Test (expected = IOException.class)
public void subscribeToDeviceMethodThrowsIfClientNotOpen(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final DeviceMethodCallback mockedDeviceMethodCB)
throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
}
};
final DeviceClient client = new DeviceClient(connString, protocol);
//act
client.subscribeToDeviceMethod(mockedDeviceMethodCB, null, mockedStatusCB, null);
}
/*
Tests_SRS_DEVICECLIENT_25_037: [**If deviceMethodCallback or deviceMethodStatusCallback is null, the function shall throw an IllegalArgumentException.**]**
*/
@Test (expected = IllegalArgumentException.class)
public void subscribeToDeviceMethodThrowsIfDeviceMethodCallbackNull(@Mocked final IotHubEventCallback mockedStatusCB)
throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
final DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.subscribeToDeviceMethod(null, null, mockedStatusCB, null);
}
@Test (expected = IllegalArgumentException.class)
public void subscribeToDeviceMethodThrowsIfDeviceMethodStatusCallbackNull(@Mocked final DeviceMethodCallback mockedDeviceMethodCB)
throws IOException, URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
final DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.subscribeToDeviceMethod(mockedDeviceMethodCB, null, null, null);
}
/*
Tests_SRS_DEVICECLIENT_25_039: [**This method shall update the deviceMethodCallback if called again, but it shall not subscribe twice.**]**
*/
@Test
public void subscribeToDeviceMethodWorksEvenWhenCalledTwice(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final DeviceMethodCallback mockedDeviceMethodCB,
@Mocked final DeviceMethod mockedMethod) throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
}
};
final DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.subscribeToDeviceMethod(mockedDeviceMethodCB, null, mockedStatusCB, null);
// act
client.subscribeToDeviceMethod(mockedDeviceMethodCB, null, mockedStatusCB, null);
// assert
new Verifications()
{
{
mockedMethod.subscribeToDeviceMethod(mockedDeviceMethodCB, any);
times = 2;
}
};
}
// Tests_SRS_DEVICECLIENT_02_015: [If optionName is null or not an option handled by the client, then it shall throw IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void setOptionWithNullOptionNameThrows()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
long someMilliseconds = 4;
// act
client.setOption(null, someMilliseconds);
}
// Tests_SRS_DEVICECLIENT_02_015: [If optionName is null or not an option handled by the client, then it shall throw IllegalArgumentException.]
@Test (expected = IllegalArgumentException.class)
public void setOptionWithUnknownOptionNameThrows()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
long someMilliseconds = 4;
// act
client.setOption("thisIsNotAHandledOption", someMilliseconds);
}
//Tests_SRS_DEVICECLIENT_02_017: [Available only for HTTP.]
@Test (expected = IllegalArgumentException.class)
public void setOptionMinimumPollingIntervalWithAMQPfails()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
long someMilliseconds = 4;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.AMQPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setOption("SetMinimumPollingInterval", someMilliseconds);
}
//Tests_SRS_DEVICECLIENT_02_018: [Value needs to have type long].
@Test (expected = IllegalArgumentException.class)
public void setOptionMinimumPollingIntervalWithStringInsteadOfLongFails()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setOption("SetMinimumPollingInterval", "thisIsNotALong");
}
//Tests_SRS_DEVICECLIENT_02_005: [Setting the option can only be done before open call.]
@Test (expected = IllegalStateException.class)
public void setOptionMinimumPollingIntervalAfterOpenFails()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
long value = 3;
// act
client.setOption("SetMinimumPollingInterval", value);
}
//Tests_SRS_DEVICECLIENT_02_016: ["SetMinimumPollingInterval" - time in milliseconds between 2 consecutive polls.]
@Test
public void setOptionMinimumPollingIntervalSucceeds()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
final long value = 3L;
// act
client.setOption("SetMinimumPollingInterval", value);
// assert
new Verifications()
{
{
mockDeviceIO.setReceivePeriodInMilliseconds(value);
}
};
}
// Tests_SRS_DEVICECLIENT_21_040: ["SetSendInterval" - time in milliseconds between 2 consecutive message sends.]
@Test
public void setOptionSendIntervalSucceeds()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
final long value = 3L;
// act
client.setOption("SetSendInterval", value);
// assert
new Verifications()
{
{
mockDeviceIO.setSendPeriodInMilliseconds(value);
}
};
}
@Test (expected = IllegalArgumentException.class)
public void setOptionSendIntervalWithStringInsteadOfLongFails()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setOption("SetSendInterval", "thisIsNotALong");
}
@Test (expected = IllegalArgumentException.class)
public void setOptionValueNullThrows()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setOption("", null);
}
//Tests_SRS_DEVICECLIENT_25_022: [**"SetSASTokenExpiryTime" should have value type long.]
@Test (expected = IllegalArgumentException.class)
public void setOptionSASTokenExpiryTimeWithStringInsteadOfLongFails()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.setOption("SetSASTokenExpiryTime", "thisIsNotALong");
}
//Tests_SRS_DEVICECLIENT_25_021: ["SetSASTokenExpiryTime" - time in seconds after which SAS Token expires.]
@Test
public void setOptionSASTokenExpiryTimeHTTPSucceeds()
throws IOException, URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_25_021: ["SetSASTokenExpiryTime" - time in seconds after which SAS Token expires.]
//Tests_SRS_DEVICECLIENT_25_024: ["SetSASTokenExpiryTime" shall restart the transport if transport is already open after updating expiry time.]
@Test
public void setOptionSASTokenExpiryTimeAfterClientOpenHTTPSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>=";
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 1;
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
Deencapsulation.invoke(mockDeviceIO, "open");
times = 2;
}
};
}
/*Tests_SRS_DEVICECLIENT_25_024: ["SetSASTokenExpiryTime" shall restart the transport
1. If the device currently uses device key and
2. If transport is already open
after updating expiry time.]
*/
@Test
public void setOptionSASTokenExpiryTimeAfterClientOpenTransportWithSasTokenSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessSignature=SharedAccessSignature sr=sample-iothub-hostname.net%2fdevices%2fsample-device-ID&sig=S3%2flPidfBF48B7%2fOFAxMOYH8rpOneq68nu61D%2fBP6fo%3d&se=1469813873";
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 0;
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
Deencapsulation.invoke(mockDeviceIO, "open");
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_25_021: ["SetSASTokenExpiryTime" - Time in secs to specify SAS Token Expiry time.]
@Test
public void setOptionSASTokenExpiryTimeAMQPSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_25_021: ["SetSASTokenExpiryTime" - time in seconds after which SAS Token expires.]
//Tests_SRS_DEVICECLIENT_25_024: ["SetSASTokenExpiryTime" shall restart the transport if transport is already open after updating expiry time.]
@Test
public void setOptionSASTokenExpiryTimeAfterClientOpenAMQPSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 1;
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
Deencapsulation.invoke(mockDeviceIO, "open");
times = 2;
}
};
}
//Tests_SRS_DEVICECLIENT_25_021: [**"SetSASTokenExpiryTime" - Time in secs to specify SAS Token Expiry time.]
@Test
public void setOptionSASTokenExpiryTimeMQTTSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations() {
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
DeviceClient client = new DeviceClient(connString, protocol);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_25_021: ["SetSASTokenExpiryTime" - time in seconds after which SAS Token expires.]
//Tests_SRS_DEVICECLIENT_25_024: ["SetSASTokenExpiryTime" shall restart the transport if transport is already open after updating expiry time.]
@Test
public void setOptionSASTokenExpiryTimeAfterClientOpenMQTTSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations() {
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockDeviceIO.close();
times = 1;
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
Deencapsulation.invoke(mockDeviceIO, "open");
times = 2;
}
};
}
// Tests_SRS_DEVICECLIENT_12_025: [If the client configured to use TransportClient the function shall use transport client closeNow() and open() for restart.]
@Test
public void setOptionWithTransportClientSASTokenExpiryTimeAfterClientOpenAMQPSucceeds()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
// assert
new Verifications()
{
{
mockTransportClient.closeNow();
times = 1;
mockConfig.getSasTokenAuthentication().setTokenValidSecs(value);
times = 1;
mockTransportClient.open();
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_027: [The function shall throw IOError if either the deviceIO or the tranportClient's open() or closeNow() throws.]
@Test (expected = IOError.class)
public void setOptionWithTransportClientSASTokenExpiryTimeAfterClientOpenAMQPThrowsTransportClientClose()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockTransportClient.closeNow();
result = new IOException();
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
}
// Tests_SRS_DEVICECLIENT_12_027: [The function shall throw IOError if either the deviceIO or the tranportClient's open() or closeNow() throws.]
@Test (expected = IOError.class)
public void setOptionWithTransportClientSASTokenExpiryTimeAfterClientOpenAMQPThrowsTransportClientOpen()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockTransportClient.open();
result = new IOException();
}
};
final String connString = "HostName=iothub.device.<EMAIL>;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
}
// Tests_SRS_DEVICECLIENT_12_029: [*SetCertificatePath" shall throw if the transportClient or deviceIO already opene.]
@Test (expected = IllegalStateException.class)
public void setOptionWithTransportClientSetCertificatePathTransportOpenedThrows()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// Deencapsulation.setField(client, "config", mockConfig);
// Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final String value = "certificatePath";
// act
client.setOption("SetCertificatePath", value);
}
// Tests_SRS_DEVICECLIENT_12_030: [*SetCertificatePath" shall udate the config on transportClient if tranportClient used.]
@Test
public void setOptionWithTransportClientSetCertificatePathSuccess()
throws IOException, URISyntaxException
{
// arrange
final String value = "certificatePath";
new NonStrictExpectations()
{
{
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.CLOSED;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockConfig.getSasTokenAuthentication();
result = mockIotHubSasTokenAuthenticationProvider;
mockIotHubSasTokenAuthenticationProvider.setPathToIotHubTrustedCert(value);
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
// act
client.setOption("SetCertificatePath", value);
new Verifications()
{
{
mockConfig.getAuthenticationType();
times = 1;
mockConfig.getSasTokenAuthentication();
times = 1;
mockIotHubSasTokenAuthenticationProvider.setPathToIotHubTrustedCert(value);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_029: [*SetCertificatePath" shall throw if the transportClient or deviceIO already open, otherwise set the path on the config.]
@Test (expected = IllegalStateException.class)
public void setOptionSetCertificatePathDeviceIOOpenedThrows()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final String value = "certificatePath";
// act
client.setOption("SetCertificatePath", value);
}
// Tests_SRS_DEVICECLIENT_12_030: [*SetCertificatePath" shall udate the config on transportClient if tranportClient used.]
@Test (expected = IllegalArgumentException.class)
public void setOptionSetCertificatePathWrongProtocolThrows()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
Deencapsulation.invoke(mockTransportClient, "getTransportClientState");
result = TransportClient.TransportClientState.OPENED;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final String value = "certificatePath";
// act
client.setOption("SetCertificatePath", value);
}
// Tests_SRS_DEVICECLIENT_12_029: [*SetCertificatePath" shall throw if the transportClient or deviceIO already open, otherwise set the path on the config.]
@Test
public void setOptionSetCertificatePathSASSuccess()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.AMQPS_WS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS_WS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final String value = "certificatePath";
// act
client.setOption("SetCertificatePath", value);
new Verifications()
{
{
mockConfig.getAuthenticationType();
times = 1;
mockConfig.getSasTokenAuthentication();
times = 1;
mockIotHubSasTokenAuthenticationProvider.setPathToIotHubTrustedCert(value);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_029: [*SetCertificatePath" shall throw if the transportClient or deviceIO already open, otherwise set the path on the config.]
@Test
public void setOptionSetCertificatePathX509Success()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = false;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.AMQPS_WS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.X509_CERTIFICATE;
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS_WS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final String value = "certificatePath";
// act
client.setOption("SetCertificatePath", value);
new Verifications()
{
{
mockConfig.getAuthenticationType();
times = 2;
mockConfig.getX509Authentication();
times = 1;
mockIotHubX509AuthenticationProvider.setPathToIotHubTrustedCert(value);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_12_027: [The function shall throw IOError if either the deviceIO or the tranportClient's open() or closeNow() throws.]
@Test (expected = IOError.class)
public void setOptionClientSASTokenExpiryTimeAfterClientOpenAMQPThrowsDeviceIOClose()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockDeviceIO.close();
result = new IOException();
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
}
// Tests_SRS_DEVICECLIENT_12_027: [The function shall throw IOError if either the deviceIO or the tranportClient's open() or closeNow() throws.]
@Test (expected = IOError.class)
public void setOptionClientSASTokenExpiryTimeAfterClientOpenAMQPThrowsTransportDeviceIOOpen()
throws IOException, URISyntaxException
{
// arrange
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getIotHubConnectionString().getSharedAccessKey();
result = anyString;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
Deencapsulation.invoke(mockDeviceIO, "open");
result = new IOException();
}
};
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final long value = 60;
// act
client.setOption("SetSASTokenExpiryTime", value);
}
// Tests_SRS_DEVICECLIENT_12_022: [If the client configured to use TransportClient the SetSendInterval shall throw IOException.]
@Test (expected = IllegalStateException.class)
public void setOptionWithTransportClientThrowsSetSendInterval()
throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
client.setOption("SetSendInterval", "thisIsNotALong");
}
// Tests_SRS_DEVICECLIENT_12_023: [If the client configured to use TransportClient the SetMinimumPollingInterval shall throw IOException.]
@Test (expected = IllegalStateException.class)
public void setOptionWithTransportClientThrowsSetMinimumPollingInterval()
throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
client.setOption("SetMinimumPollingInterval", "thisIsNotALong");
}
//Tests_SRS_DEVICECLIENT_34_055: [If the provided connection string contains an expired SAS token, a SecurityException shall be thrown.]
@Test (expected = SecurityException.class)
public void deviceClientInitializedWithExpiredTokenThrowsSecurityException() throws SecurityException, URISyntaxException
{
//This token will always be expired
final Long expiryTime = 0L;
final String expiredConnString = "HostName=iothub.device.com;DeviceId=2;SharedAccessSignature=SharedAccessSignature sr=hub.azure-devices.net%2Fdevices%2F2&sig=3V1oYPdtyhGPHDDpjS2SnwxoU7CbI%2BYxpLjsecfrtgY%3D&se=" + expiryTime;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
new NonStrictExpectations()
{
{
new IotHubConnectionString(anyString);
result = new SecurityException();
mockConfig.getIotHubConnectionString().getSharedAccessToken();
result = expiredConnString;
}
};
// act
DeviceClient client = new DeviceClient(expiredConnString, protocol);
}
//Tests_SRS_DEVICECLIENT_34_044: [**If the SAS token has expired before this call, throw a Security Exception**]
@Test (expected = SecurityException.class)
public void tokenExpiresAfterDeviceClientInitializedBeforeOpen() throws SecurityException, URISyntaxException, IOException
{
final Long expiryTime = Long.MAX_VALUE;
final String connString = "HostName=iothub.device.com;DeviceId=2;SharedAccessSignature=SharedAccessSignature sr=hub.azure-devices.net%2Fdevices%2F2&sig=3V1oYPdtyhGPHDDpjS2SnwxoU7CbI%2BYxpLjsecfrtgY%3D&se=" + expiryTime;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
new NonStrictExpectations()
{
{
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.SAS_TOKEN;
mockConfig.getSasTokenAuthentication().isRenewalNecessary();
result = true;
mockConfig.getIotHubConnectionString().getSharedAccessToken();
result = "SharedAccessSignature sr=hub.azure-devices.net%2Fdevices%2F2&sig=3V1oYPdtyhGPHDDpjS2SnwxoU7CbI%2BYxpLjsecfrtgY%3D&se=" + expiryTime;
}
};
// act
client.open();
}
/* Tests_SRS_DEVICECLIENT_21_044: [The uploadToBlobAsync shall asynchronously upload the stream in `inputStream` to the blob in `destinationBlobName`.] */
/* Tests_SRS_DEVICECLIENT_21_048: [If there is no instance of the FileUpload, the uploadToBlobAsync shall create a new instance of the FileUpload.] */
/* Tests_SRS_DEVICECLIENT_21_050: [The uploadToBlobAsync shall start the stream upload process, by calling uploadToBlobAsync on the FileUpload class.] */
@Test
public void startFileUploadSucceeds(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
result = mockedFileUpload;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
// assert
new Verifications()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
times = 1;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_054: [If the fileUpload is not null, the closeNow shall call closeNow on fileUpload.] */
@Test
public void closeNowClosesFileUploadSucceeds(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
result = mockedFileUpload;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.open();
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
// act
client.closeNow();
// assert
new Verifications()
{
{
Deencapsulation.invoke(mockedFileUpload, "closeNow");
times = 1;
}
};
}
/* Tests_SRS_DEVICECLIENT_21_045: [If the `callback` is null, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadNullCallbackThrows(@Mocked final InputStream mockInputStream,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, null, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_046: [If the `inputStream` is null, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadNullInputStreamThrows(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, (InputStream) null, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_052: [If the `streamLength` is negative, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadNegativeLengthThrows(@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final InputStream mockInputStream,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, -1, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_047: [If the `destinationBlobName` is null, empty, or not valid, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadNullBlobNameThrows(@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(null, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_047: [If the `destinationBlobName` is null, empty, or not valid, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadEmptyBlobNameThrows(@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync("", mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_047: [If the `destinationBlobName` is null, empty, or not valid, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadInvalidUTF8BlobNameThrows(@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid\u1234/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_047: [If the `destinationBlobName` is null, empty, or not valid, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadInvalidBigBlobNameThrows(@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
StringBuilder bigBlobName = new StringBuilder();
String directory = "directory/";
final long streamLength = 100;
// create a blob name bigger than 1024 characters.
for (int i = 0; i < (2000/directory.length()); i++)
{
bigBlobName.append(directory);
}
bigBlobName.append("image.jpg");
final String destinationBlobName = bigBlobName.toString();
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_047: [If the `destinationBlobName` is null, empty, or not valid, the uploadToBlobAsync shall throw IllegalArgumentException.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadInvalidPathBlobNameThrows(@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
StringBuilder bigBlobName = new StringBuilder();
String directory = "a/";
final long streamLength = 100;
// create a blob name with more than 254 path segments.
for (int i = 0; i < 300; i++)
{
bigBlobName.append(directory);
}
bigBlobName.append("image.jpg");
final String destinationBlobName = bigBlobName.toString();
deviceClientInstanceExpectation(connString, protocol);
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_048: [If there is no instance of the FileUpload, the uploadToBlobAsync shall create a new instance of the FileUpload.] */
@Test
public void startFileUploadOneFileUploadInstanceSucceeds(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
result = mockedFileUpload;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
};
DeviceClient client = new DeviceClient(connString, protocol);
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
// assert
new Verifications()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
times = 1;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
times = 2;
}
};
}
//Tests_SRS_DEVICECLIENT_99_001: [The registerConnectionStateCallback shall register the callback with the Device IO.]
//Tests_SRS_DEVICECLIENT_99_002: [The registerConnectionStateCallback shall register the callback even if the client is not open.]
@Test
public void registerConnectionStateCallback(@Mocked final IotHubConnectionStateCallback mockedStateCB) throws URISyntaxException, IOException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final DeviceClient client = new DeviceClient(connString, protocol);
client.open();
//act
client.registerConnectionStateCallback(mockedStateCB, null);
//assert
new Verifications()
{
{
mockDeviceIO.registerConnectionStateCallback(mockedStateCB, null);
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_99_003: [If the callback is null the method shall throw an IllegalArgument exception.]
@Test (expected = IllegalArgumentException.class)
public void registerConnectionStateCallbackNullCallback()
throws IllegalArgumentException, URISyntaxException, IOException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final DeviceClient client = new DeviceClient(connString, protocol);
//act
client.registerConnectionStateCallback(null, null);
}
/* Tests_SRS_DEVICECLIENT_21_049: [If uploadToBlobAsync failed to create a new instance of the FileUpload, it shall bypass the exception.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadNewInstanceThrows(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
result = new IllegalArgumentException();
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
// Tests_SRS_DEVICECLIENT_34_066: [If this function is called when the device client is using x509 authentication, an UnsupportedOperationException shall be thrown.]
@Test (expected = UnsupportedOperationException.class)
public void startFileUploadUploadToBlobAsyncAuthTypeThrows(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.X509_CERTIFICATE;
}
};
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
/* Tests_SRS_DEVICECLIENT_21_051: [If uploadToBlobAsync failed to start the upload using the FileUpload, it shall bypass the exception.] */
@Test (expected = IllegalArgumentException.class)
public void startFileUploadUploadToBlobAsyncThrows(@Mocked final FileUpload mockedFileUpload,
@Mocked final InputStream mockInputStream,
@Mocked final IotHubEventCallback mockedStatusCB,
@Mocked final PropertyCallBack mockedPropertyCB) throws IOException, URISyntaxException, TransportException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
final String destinationBlobName = "valid/blob/name.txt";
final long streamLength = 100;
deviceClientInstanceExpectation(connString, protocol);
new NonStrictExpectations()
{
{
Deencapsulation.newInstance(FileUpload.class, mockConfig);
result = mockedFileUpload;
Deencapsulation.invoke(mockedFileUpload, "uploadToBlobAsync",
destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
result = new IllegalArgumentException();
}
};
DeviceClient client = new DeviceClient(connString, protocol);
// act
client.uploadToBlobAsync(destinationBlobName, mockInputStream, streamLength, mockedStatusCB, mockedPropertyCB);
}
//Tests_SRS_DEVICECLIENT_34_065: [""SetSASTokenExpiryTime" if this option is called when not using sas token authentication, an IllegalStateException shall be thrown.*]
@Test (expected = IllegalStateException.class)
public void setOptionSASTokenExpiryTimeWhenNotUsingSasTokenAuthThrows() throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
new NonStrictExpectations()
{
{
mockDeviceIO.isOpen();
result = true;
mockDeviceIO.getProtocol();
result = IotHubClientProtocol.HTTPS;
mockConfig.getAuthenticationType();
result = DeviceClientConfig.AuthType.X509_CERTIFICATE;
}
};
DeviceClient client = new DeviceClient(connString, protocol, "someCert", false, "someKey", false);
// act
client.setOption("SetSASTokenExpiryTime", 25L);
}
// Tests_SRS_DEVICECLIENT_12_002: [The function shall return with he current value of client config.]
@Test
public void getConfig() throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;" + "SharedAccessKey=<KEY>;
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.setField(client, "config", mockConfig);
// act
DeviceClientConfig deviceClientConfig = Deencapsulation.invoke(client, "getConfig");
// assert
assertEquals(deviceClientConfig, mockConfig);
}
// Tests_SRS_DEVICECLIENT_12_003: [The function shall return with he current value of the client's underlying DeviceIO.]
@Test
public void getGetDeviceIO() throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;" + "SharedAccessKey=<KEY>=";
DeviceClient client = new DeviceClient(connString, mockTransportClient);
Deencapsulation.invoke(client, "setDeviceIO", mockDeviceIO);
// act
DeviceIO deviceIO = Deencapsulation.invoke(client, "getDeviceIO");
// assert
assertEquals(deviceIO, mockDeviceIO);
}
// Tests_SRS_DEVICECLIENT_12_004: [The function shall set the client's underlying DeviceIO to the value of the given deviceIO parameter.]
@Test
public void setGetDeviceIO() throws URISyntaxException
{
// arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;" + "SharedAccessKey=<KEY>=";
DeviceClient client = new DeviceClient(connString, mockTransportClient);
// act
Deencapsulation.invoke(client, "setDeviceIO", mockDeviceIO);
// assert
DeviceIO deviceIO = Deencapsulation.getField(client, "deviceIO");
assertEquals(deviceIO, mockDeviceIO);
}
// Tests_SRS_DEVICECLIENT_12_028: [The constructor shall shall set the config, deviceIO and tranportClient to null.]
@Test
public void unusedConstructor()
{
// act
DeviceClient client = Deencapsulation.newInstance(DeviceClient.class);
// assert
assertNull(Deencapsulation.getField(client, "config"));
assertNull(Deencapsulation.getField(client, "deviceIO"));
}
//Tests_SRS_DEVICECLIENT_34_068: [If the callback is null the method shall throw an IllegalArgument exception.]
@Test (expected = IllegalArgumentException.class)
public void registerConnectionStatusChangeCallbackThrowsForNullCallback() throws URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=adjkl234j52=;";
DeviceClient client = new DeviceClient(connString, IotHubClientProtocol.AMQPS);
//act
client.registerConnectionStatusChangeCallback(null, new Object());
}
//Tests_SRS_DEVICECLIENT_34_069: [This function shall register the provided callback and context with its device IO instance.]
@Test
public void registerConnectionStatusChangeCallbackRegistersCallbackWithDeviceIO() throws URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;CredentialScope=Device;DeviceId=testdevice;SharedAccessKey=<KEY>=;";
DeviceClient client = new DeviceClient(connString, IotHubClientProtocol.AMQPS);
Deencapsulation.setField(client, "deviceIO", mockDeviceIO);
final Object context = new Object();
//act
client.registerConnectionStatusChangeCallback(mockedIotHubConnectionStatusChangeCallback, context);
//assert
new Verifications()
{
{
mockDeviceIO.registerConnectionStatusChangeCallback(mockedIotHubConnectionStatusChangeCallback, context);
times = 1;
}
};
}
//Tests_SRS_DEVICECLIENT_28_001: [The function shall set the device config's RetryPolicy .]
@Test
public void setRetryPolicySetPolicy() throws URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>=";
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
Deencapsulation.setField(client, "config", mockConfig);
//act
client.setRetryPolicy(new ExponentialBackoffWithJitter());
//assert
new Verifications()
{
{
mockConfig.setRetryPolicy((RetryPolicy) any);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_34_070: [The function shall set the device config's operation timeout .]
@Test
public void setDeviceOperationTimeoutSetsConfig() throws URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
final long expectedTimeout = 1034;
Deencapsulation.setField(client, "config", mockConfig);
//act
client.setOperationTimeout(expectedTimeout);
//assert
new Verifications()
{
{
Deencapsulation.invoke(mockConfig, "setOperationTimeout", expectedTimeout);
times = 1;
}
};
}
// Tests_SRS_DEVICECLIENT_34_071: [This function shall return the product info saved in config.]
@Test
public void getProductInfoFetchesFromConfig() throws URISyntaxException
{
//arrange
final String connString = "HostName=iothub.device.com;CredentialType=SharedAccessKey;DeviceId=testdevice;"
+ "SharedAccessKey=<KEY>;
final IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
DeviceClient client = new DeviceClient(connString, protocol);
new StrictExpectations()
{
{
mockConfig.getProductInfo();
result = mockedProductInfo;
}
};
//act
ProductInfo productInfo = client.getProductInfo();
//assert
assertEquals(mockedProductInfo, productInfo);
}
}
| 0 | java | error | 0 |
|
package com.hintersatz.blogapp.app.security;
import com.hintersatz.blogapp.backend.model.User;
import com.hintersatz.blogapp.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class UserDetailsServiceImp implements UserDetailsService {
private final UserRepository userRepository;
@Autowired
public UserDetailsServiceImp(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Optional<User> user = userRepository.findByUsername(s);
if (!user.isPresent()) {
throw new UsernameNotFoundException("No user present with given username " + s);
} else {
return user.get();
}
}
}
| package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_5.IMPORT_6.IMPORT_7;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_5.IMPORT_8.IMPORT_9;
import IMPORT_10.IMPORT_11.IMPORT_12.IMPORT_13.IMPORT_14.IMPORT_15;
import IMPORT_10.IMPORT_11.IMPORT_4.IMPORT_16.IMPORT_17.IMPORT_18;
import IMPORT_10.IMPORT_11.IMPORT_4.IMPORT_16.IMPORT_17.IMPORT_19;
import IMPORT_10.IMPORT_11.IMPORT_4.IMPORT_16.IMPORT_17.IMPORT_20;
import IMPORT_10.IMPORT_11.IMPORT_21.IMPORT_22;
import IMPORT_23.IMPORT_24.IMPORT_25;
@IMPORT_22
public class CLASS_0 implements IMPORT_19 {
private final IMPORT_9 VAR_0;
@IMPORT_15
public CLASS_0(IMPORT_9 VAR_0) {
this.VAR_0 = VAR_0;
}
@VAR_1
public IMPORT_18 FUNC_0(CLASS_1 VAR_2) throws IMPORT_20 {
IMPORT_25<IMPORT_7> VAR_3 = VAR_0.FUNC_1(VAR_2);
if (!VAR_3.FUNC_2()) {
throw new IMPORT_20("No user present with given username " + VAR_2);
} else {
return VAR_3.FUNC_3();
}
}
}
| 0.996197 | {'IMPORT_0': 'com', 'IMPORT_1': 'hintersatz', 'IMPORT_2': 'blogapp', 'IMPORT_3': 'app', 'IMPORT_4': 'security', 'IMPORT_5': 'backend', 'IMPORT_6': 'model', 'IMPORT_7': 'User', 'IMPORT_8': 'repository', 'IMPORT_9': 'UserRepository', 'IMPORT_10': 'org', 'IMPORT_11': 'springframework', 'IMPORT_12': 'beans', 'IMPORT_13': 'factory', 'IMPORT_14': 'annotation', 'IMPORT_15': 'Autowired', 'IMPORT_16': 'core', 'IMPORT_17': 'userdetails', 'IMPORT_18': 'UserDetails', 'IMPORT_19': 'UserDetailsService', 'IMPORT_20': 'UsernameNotFoundException', 'IMPORT_21': 'stereotype', 'IMPORT_22': 'Service', 'IMPORT_23': 'java', 'IMPORT_24': 'util', 'IMPORT_25': 'Optional', 'CLASS_0': 'UserDetailsServiceImp', 'VAR_0': 'userRepository', 'VAR_1': 'Override', 'FUNC_0': 'loadUserByUsername', 'CLASS_1': 'String', 'VAR_2': 's', 'VAR_3': 'user', 'FUNC_1': 'findByUsername', 'FUNC_2': 'isPresent', 'FUNC_3': 'get'} | java | OOP | 83.87% |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.cms.model.v20190101;
import com.aliyuncs.RpcAcsRequest;
import java.util.List;
import com.aliyuncs.http.MethodType;
/**
* @author auto create
* @version
*/
public class PutMetricRuleTargetsRequest extends RpcAcsRequest<PutMetricRuleTargetsResponse> {
private List<Targets> targetss;
private String ruleId;
public PutMetricRuleTargetsRequest() {
super("Cms", "2019-01-01", "PutMetricRuleTargets", "Cms");
setMethod(MethodType.POST);
}
public List<Targets> getTargetss() {
return this.targetss;
}
public void setTargetss(List<Targets> targetss) {
this.targetss = targetss;
if (targetss != null) {
for (int depth1 = 0; depth1 < targetss.size(); depth1++) {
putQueryParameter("Targets." + (depth1 + 1) + ".Level" , targetss.get(depth1).getLevel());
putQueryParameter("Targets." + (depth1 + 1) + ".Id" , targetss.get(depth1).getId());
putQueryParameter("Targets." + (depth1 + 1) + ".Arn" , targetss.get(depth1).getArn());
putQueryParameter("Targets." + (depth1 + 1) + ".JsonParams" , targetss.get(depth1).getJsonParams());
}
}
}
public String getRuleId() {
return this.ruleId;
}
public void setRuleId(String ruleId) {
this.ruleId = ruleId;
if(ruleId != null){
putQueryParameter("RuleId", ruleId);
}
}
public static class Targets {
private String level;
private String id;
private String arn;
private String jsonParams;
public String getLevel() {
return this.level;
}
public void setLevel(String level) {
this.level = level;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getArn() {
return this.arn;
}
public void setArn(String arn) {
this.arn = arn;
}
public String getJsonParams() {
return this.jsonParams;
}
public void setJsonParams(String jsonParams) {
this.jsonParams = jsonParams;
}
}
@Override
public Class<PutMetricRuleTargetsResponse> getResponseClass() {
return PutMetricRuleTargetsResponse.class;
}
}
| /*
* 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 IMPORT_0.aliyuncs.IMPORT_1.IMPORT_2.IMPORT_3;
import IMPORT_0.aliyuncs.IMPORT_4;
import IMPORT_5.IMPORT_6.List;
import IMPORT_0.aliyuncs.http.IMPORT_7;
/**
* @author auto create
* @version
*/
public class PutMetricRuleTargetsRequest extends IMPORT_4<CLASS_0> {
private List<CLASS_1> VAR_0;
private CLASS_2 VAR_1;
public PutMetricRuleTargetsRequest() {
super("Cms", "2019-01-01", "PutMetricRuleTargets", "Cms");
FUNC_0(IMPORT_7.POST);
}
public List<CLASS_1> FUNC_1() {
return this.VAR_0;
}
public void FUNC_2(List<CLASS_1> VAR_0) {
this.VAR_0 = VAR_0;
if (VAR_0 != null) {
for (int VAR_2 = 0; VAR_2 < VAR_0.FUNC_3(); VAR_2++) {
FUNC_4("Targets." + (VAR_2 + 1) + ".Level" , VAR_0.FUNC_5(VAR_2).FUNC_6());
FUNC_4("Targets." + (VAR_2 + 1) + ".Id" , VAR_0.FUNC_5(VAR_2).getId());
FUNC_4("Targets." + (VAR_2 + 1) + ".Arn" , VAR_0.FUNC_5(VAR_2).FUNC_7());
FUNC_4("Targets." + (VAR_2 + 1) + ".JsonParams" , VAR_0.FUNC_5(VAR_2).FUNC_8());
}
}
}
public CLASS_2 FUNC_9() {
return this.VAR_1;
}
public void FUNC_10(CLASS_2 VAR_1) {
this.VAR_1 = VAR_1;
if(VAR_1 != null){
FUNC_4("RuleId", VAR_1);
}
}
public static class CLASS_1 {
private CLASS_2 VAR_3;
private CLASS_2 VAR_4;
private CLASS_2 arn;
private CLASS_2 VAR_5;
public CLASS_2 FUNC_6() {
return this.VAR_3;
}
public void FUNC_11(CLASS_2 VAR_3) {
this.VAR_3 = VAR_3;
}
public CLASS_2 getId() {
return this.VAR_4;
}
public void FUNC_12(CLASS_2 VAR_4) {
this.VAR_4 = VAR_4;
}
public CLASS_2 FUNC_7() {
return this.arn;
}
public void setArn(CLASS_2 arn) {
this.arn = arn;
}
public CLASS_2 FUNC_8() {
return this.VAR_5;
}
public void FUNC_13(CLASS_2 VAR_5) {
this.VAR_5 = VAR_5;
}
}
@VAR_6
public Class<CLASS_0> getResponseClass() {
return CLASS_0.class;
}
}
| 0.57133 | {'IMPORT_0': 'com', 'IMPORT_1': 'cms', 'IMPORT_2': 'model', 'IMPORT_3': 'v20190101', 'IMPORT_4': 'RpcAcsRequest', 'IMPORT_5': 'java', 'IMPORT_6': 'util', 'IMPORT_7': 'MethodType', 'CLASS_0': 'PutMetricRuleTargetsResponse', 'CLASS_1': 'Targets', 'VAR_0': 'targetss', 'CLASS_2': 'String', 'VAR_1': 'ruleId', 'FUNC_0': 'setMethod', 'FUNC_1': 'getTargetss', 'FUNC_2': 'setTargetss', 'VAR_2': 'depth1', 'FUNC_3': 'size', 'FUNC_4': 'putQueryParameter', 'FUNC_5': 'get', 'FUNC_6': 'getLevel', 'FUNC_7': 'getArn', 'FUNC_8': 'getJsonParams', 'FUNC_9': 'getRuleId', 'FUNC_10': 'setRuleId', 'VAR_3': 'level', 'VAR_4': 'id', 'VAR_5': 'jsonParams', 'FUNC_11': 'setLevel', 'FUNC_12': 'setId', 'FUNC_13': 'setJsonParams', 'VAR_6': 'Override'} | java | Hibrido | 44.01% |
/**
* Class Description: Set some public setting of classes, which were used
* oftenly
*/
public class RecordStoreConfig {
private static RecordStore operation_RS = null;
private UIController controller = null;
public static String RECORDSTORE_OPERATIONNAME = "dictoperation";
public RecordStoreConfig(UIController controller) throws IOException,RecordStoreException {
//#debug debug
System.out.println("Set dictrecord Constructor");
this.controller = controller;
openRS();
}
/** Open RecordStore, if not then create new */
private synchronized void openRS() throws IOException, RecordStoreException {
try {
operation_RS = RecordStore.openRecordStore(
RECORDSTORE_OPERATIONNAME, true);
//TODO delete later, only for test
//deleteDatabase();
if (operation_RS.getNumRecords() == 0) {
//#debug debug
System.out.println("No record");
// If these are no record, load the default record of server
DefaultRS();
} else {
//#debug debug
System.out.println("Find record");
}
} catch (Exception e) {
//#debug error
System.out.println("Err openRS: "+ e.getMessage());
}
}
// Close RecordStore
public synchronized void closeRS() {
if (operation_RS != null) {
try {
operation_RS.closeRecordStore();
operation_RS = null;
} catch (RecordStoreException ex) {
//#debug error
System.out.println("Error in closeRS: " + ex.getMessage());
}
}
}
/*
* At the beginning of loading, if there are no record in the recordstore,we
* can add some default operation to it.
*/
private void DefaultRS() throws IOException, RecordStoreException {
System.out.println("load the default operation");
byte data[] = null;
ByteArrayOutputStream baos = null;
DataOutputStream dos = null;
try {
baos = new ByteArrayOutputStream();
dos = new DataOutputStream(baos);
dos.writeBoolean(Setting.btips);
dos.writeInt(Setting.resultmax);
dos.writeInt(Setting.approlevel);
dos.writeBoolean(Setting.dbarray0);
dos.writeBoolean(Setting.dbarray1);
/* dos.writeBoolean(Setting.dbarray2);
dos.writeBoolean(Setting.lang0);
dos.writeBoolean(Setting.lang1);
dos.writeBoolean(Setting.lang2);*/
dos.writeBoolean(Setting.net0);
dos.writeBoolean(Setting.net1);
dos.writeUTF(CommonFunc.writeMachineCode());
dos.writeBoolean(Setting.bRegister);
data = baos.toByteArray();
operation_RS.addRecord(data, 0, data.length);
} catch (Exception e) {
//#debug error
System.out.println("Er in DefaultRS: " + e.getMessage());
}finally{
try{
if(baos != null){
baos.close();
}
if(dos != null){
dos.close();
}
data = null;
}catch(Exception e){
//ignore
}
}
}
/** Add Record */
/*
* addRSb here will be used only once when the user first set the operation
* and initialize the recordstore
*/
public boolean addRSb(ItemOption operitem) {
if(operation_RS == null) return false;
byte data[] = null;
ByteArrayOutputStream baos = null;
DataOutputStream dos = null;
try {
baos = new ByteArrayOutputStream();
dos = new DataOutputStream(baos);
dos.writeBoolean(operitem.gettips());
dos.writeInt(operitem.getresultmax());
dos.writeInt(operitem.getapprolevel());
dos.writeBoolean(operitem.getdbarray0());
dos.writeBoolean(operitem.getdbarray1());
/* dos.writeBoolean(operitem.getdbarray2());
dos.writeBoolean(operitem.getlang0());
dos.writeBoolean(operitem.getlang1());
dos.writeBoolean(operitem.getlang2());*/
dos.writeBoolean(operitem.getnet0());
dos.writeBoolean(operitem.getnet1());
dos.writeUTF(operitem.getMachineCode());
dos.writeBoolean(operitem.getRegister());
data = baos.toByteArray();
operation_RS.addRecord(data, 0, data.length);
return true;
} catch (Exception e) {
//#debug error
System.out.println("Error1 in addRSb: " + e.getMessage());
return false;
}
finally{
try{
if(baos != null){
baos.close();
}
if(dos != null){
dos.close();
}
data = null;
}catch(Exception e){
//ignore
}
closeRS();
}
}
/** update the Record */
public boolean updateRS(ItemOption operitem) {
byte data[] = null;
ByteArrayOutputStream baos = null;
DataOutputStream dos = null;
try {
baos = new ByteArrayOutputStream();
dos = new DataOutputStream(baos);
dos.writeBoolean(operitem.gettips());
dos.writeInt(operitem.getresultmax());
dos.writeInt(operitem.getapprolevel());
dos.writeBoolean(operitem.getdbarray0());
dos.writeBoolean(operitem.getdbarray1());
/* dos.writeBoolean(operitem.getdbarray2());
dos.writeBoolean(operitem.getlang0());
dos.writeBoolean(operitem.getlang1());
dos.writeBoolean(operitem.getlang2());*/
dos.writeBoolean(operitem.getnet0());
dos.writeBoolean(operitem.getnet1());
dos.writeUTF(operitem.getMachineCode());
dos.writeBoolean(operitem.getRegister());
data = baos.toByteArray();
// only the first record was used
operation_RS.setRecord(1, data, 0, data.length);
return true;
} catch (Exception e) {
//#debug error
System.out.println("Err in updateRS: " + e.getMessage());
return false;
}finally{
try{
if(baos != null){
baos.close();
}
if(dos != null){
dos.close();
}
data = null;
}catch(Exception e){
//ignore
}
closeRS();
}
}
/**
* visit one Record id==1, because only the first record will be used always
*/
public ItemOption getRS() {
ItemOption operitem = new ItemOption();
ByteArrayInputStream bais = null;
DataInputStream dis = null;
byte data[] = null;
try {
if (operation_RS.getNumRecords() > 0) {
data = operation_RS.getRecord(1);
bais = new ByteArrayInputStream(data);
dis = new DataInputStream(bais);
operitem.settips(dis.readBoolean());
operitem.setresultmax(dis.readInt());
operitem.setapprolevel(dis.readInt());
operitem.setdbarray0(dis.readBoolean());
operitem.setdbarray1(dis.readBoolean());
/* operitem.setdbarray2(dis.readBoolean());
operitem.setlang0(dis.readBoolean());
operitem.setlang1(dis.readBoolean());
operitem.setlang2(dis.readBoolean());*/
operitem.setnet0(dis.readBoolean());
operitem.setnet1(dis.readBoolean());
operitem.setMachineCode(dis.readUTF());
operitem.setRegister(dis.readBoolean());
}
} catch (RecordStoreException ex) {
//#debug error
System.out.println("Error in getRS:" + ex.getMessage());
}catch (Exception e) {
//#debug error
System.out.println("Error in getRS:" + e.getMessage());
}finally{
try{
if(bais != null){
bais.close();
}
if(dis != null){
dis.close();
}
data = null;
}catch(Exception e){
//ignore
}
}
return operitem;
}
public boolean deleteRSb(int id) {
try {
System.out.println("Now delete record: " + id);
operation_RS.deleteRecord(id);
return true;
} catch (Exception e) {
//#debug error
System.out.println("Error in deleteRSb:" + e.getMessage());
return false;
}
}
public boolean deleteDatabase() {
try {
//#debug debug
System.out.println("Now delete database");
if(operation_RS!=null){
closeRS();
}
RecordStore.deleteRecordStore(RECORDSTORE_OPERATIONNAME);
return true;
} catch (Exception e) {
//#debug error
System.out.println("Error in deleteDatabase:" + e.getMessage());
return false;
}
}
} | /**
* Class Description: Set some public setting of classes, which were used
* oftenly
*/
public class RecordStoreConfig {
private static CLASS_0 VAR_1 = null;
private CLASS_1 controller = null;
public static String VAR_2 = "dictoperation";
public RecordStoreConfig(CLASS_1 controller) throws IOException,CLASS_2 {
//#debug debug
VAR_3.VAR_4.println("Set dictrecord Constructor");
this.controller = controller;
openRS();
}
/** Open RecordStore, if not then create new */
private synchronized void openRS() throws IOException, CLASS_2 {
try {
VAR_1 = VAR_0.openRecordStore(
VAR_2, true);
//TODO delete later, only for test
//deleteDatabase();
if (VAR_1.FUNC_0() == 0) {
//#debug debug
VAR_3.VAR_4.println("No record");
// If these are no record, load the default record of server
FUNC_1();
} else {
//#debug debug
VAR_3.VAR_4.println("Find record");
}
} catch (Exception e) {
//#debug error
VAR_3.VAR_4.println("Err openRS: "+ e.FUNC_2());
}
}
// Close RecordStore
public synchronized void FUNC_3() {
if (VAR_1 != null) {
try {
VAR_1.FUNC_4();
VAR_1 = null;
} catch (CLASS_2 VAR_5) {
//#debug error
VAR_3.VAR_4.println("Error in closeRS: " + VAR_5.FUNC_2());
}
}
}
/*
* At the beginning of loading, if there are no record in the recordstore,we
* can add some default operation to it.
*/
private void FUNC_1() throws IOException, CLASS_2 {
VAR_3.VAR_4.println("load the default operation");
byte data[] = null;
CLASS_3 baos = null;
CLASS_4 dos = null;
try {
baos = new CLASS_3();
dos = new CLASS_4(baos);
dos.FUNC_5(VAR_6.VAR_7);
dos.FUNC_6(VAR_6.VAR_8);
dos.FUNC_6(VAR_6.VAR_9);
dos.FUNC_5(VAR_6.VAR_10);
dos.FUNC_5(VAR_6.VAR_11);
/* dos.writeBoolean(Setting.dbarray2);
dos.writeBoolean(Setting.lang0);
dos.writeBoolean(Setting.lang1);
dos.writeBoolean(Setting.lang2);*/
dos.FUNC_5(VAR_6.VAR_12);
dos.FUNC_5(VAR_6.VAR_13);
dos.FUNC_7(CommonFunc.writeMachineCode());
dos.FUNC_5(VAR_6.bRegister);
data = baos.FUNC_8();
VAR_1.FUNC_9(data, 0, data.length);
} catch (Exception e) {
//#debug error
VAR_3.VAR_4.println("Er in DefaultRS: " + e.FUNC_2());
}finally{
try{
if(baos != null){
baos.close();
}
if(dos != null){
dos.close();
}
data = null;
}catch(Exception e){
//ignore
}
}
}
/** Add Record */
/*
* addRSb here will be used only once when the user first set the operation
* and initialize the recordstore
*/
public boolean addRSb(CLASS_5 VAR_14) {
if(VAR_1 == null) return false;
byte data[] = null;
CLASS_3 baos = null;
CLASS_4 dos = null;
try {
baos = new CLASS_3();
dos = new CLASS_4(baos);
dos.FUNC_5(VAR_14.gettips());
dos.FUNC_6(VAR_14.getresultmax());
dos.FUNC_6(VAR_14.FUNC_10());
dos.FUNC_5(VAR_14.FUNC_11());
dos.FUNC_5(VAR_14.FUNC_12());
/* dos.writeBoolean(operitem.getdbarray2());
dos.writeBoolean(operitem.getlang0());
dos.writeBoolean(operitem.getlang1());
dos.writeBoolean(operitem.getlang2());*/
dos.FUNC_5(VAR_14.FUNC_13());
dos.FUNC_5(VAR_14.FUNC_14());
dos.FUNC_7(VAR_14.FUNC_15());
dos.FUNC_5(VAR_14.FUNC_16());
data = baos.FUNC_8();
VAR_1.FUNC_9(data, 0, data.length);
return true;
} catch (Exception e) {
//#debug error
VAR_3.VAR_4.println("Error1 in addRSb: " + e.FUNC_2());
return false;
}
finally{
try{
if(baos != null){
baos.close();
}
if(dos != null){
dos.close();
}
data = null;
}catch(Exception e){
//ignore
}
FUNC_3();
}
}
/** update the Record */
public boolean updateRS(CLASS_5 VAR_14) {
byte data[] = null;
CLASS_3 baos = null;
CLASS_4 dos = null;
try {
baos = new CLASS_3();
dos = new CLASS_4(baos);
dos.FUNC_5(VAR_14.gettips());
dos.FUNC_6(VAR_14.getresultmax());
dos.FUNC_6(VAR_14.FUNC_10());
dos.FUNC_5(VAR_14.FUNC_11());
dos.FUNC_5(VAR_14.FUNC_12());
/* dos.writeBoolean(operitem.getdbarray2());
dos.writeBoolean(operitem.getlang0());
dos.writeBoolean(operitem.getlang1());
dos.writeBoolean(operitem.getlang2());*/
dos.FUNC_5(VAR_14.FUNC_13());
dos.FUNC_5(VAR_14.FUNC_14());
dos.FUNC_7(VAR_14.FUNC_15());
dos.FUNC_5(VAR_14.FUNC_16());
data = baos.FUNC_8();
// only the first record was used
VAR_1.setRecord(1, data, 0, data.length);
return true;
} catch (Exception e) {
//#debug error
VAR_3.VAR_4.println("Err in updateRS: " + e.FUNC_2());
return false;
}finally{
try{
if(baos != null){
baos.close();
}
if(dos != null){
dos.close();
}
data = null;
}catch(Exception e){
//ignore
}
FUNC_3();
}
}
/**
* visit one Record id==1, because only the first record will be used always
*/
public CLASS_5 FUNC_17() {
CLASS_5 VAR_14 = new CLASS_5();
ByteArrayInputStream VAR_15 = null;
CLASS_6 VAR_16 = null;
byte data[] = null;
try {
if (VAR_1.FUNC_0() > 0) {
data = VAR_1.getRecord(1);
VAR_15 = new ByteArrayInputStream(data);
VAR_16 = new CLASS_6(VAR_15);
VAR_14.settips(VAR_16.readBoolean());
VAR_14.setresultmax(VAR_16.readInt());
VAR_14.FUNC_18(VAR_16.readInt());
VAR_14.setdbarray0(VAR_16.readBoolean());
VAR_14.FUNC_19(VAR_16.readBoolean());
/* operitem.setdbarray2(dis.readBoolean());
operitem.setlang0(dis.readBoolean());
operitem.setlang1(dis.readBoolean());
operitem.setlang2(dis.readBoolean());*/
VAR_14.FUNC_20(VAR_16.readBoolean());
VAR_14.setnet1(VAR_16.readBoolean());
VAR_14.FUNC_21(VAR_16.FUNC_22());
VAR_14.FUNC_23(VAR_16.readBoolean());
}
} catch (CLASS_2 VAR_5) {
//#debug error
VAR_3.VAR_4.println("Error in getRS:" + VAR_5.FUNC_2());
}catch (Exception e) {
//#debug error
VAR_3.VAR_4.println("Error in getRS:" + e.FUNC_2());
}finally{
try{
if(VAR_15 != null){
VAR_15.close();
}
if(VAR_16 != null){
VAR_16.close();
}
data = null;
}catch(Exception e){
//ignore
}
}
return VAR_14;
}
public boolean FUNC_24(int VAR_17) {
try {
VAR_3.VAR_4.println("Now delete record: " + VAR_17);
VAR_1.deleteRecord(VAR_17);
return true;
} catch (Exception e) {
//#debug error
VAR_3.VAR_4.println("Error in deleteRSb:" + e.FUNC_2());
return false;
}
}
public boolean FUNC_25() {
try {
//#debug debug
VAR_3.VAR_4.println("Now delete database");
if(VAR_1!=null){
FUNC_3();
}
VAR_0.FUNC_26(VAR_2);
return true;
} catch (Exception e) {
//#debug error
VAR_3.VAR_4.println("Error in deleteDatabase:" + e.FUNC_2());
return false;
}
}
} | 0.552417 | {'CLASS_0': 'RecordStore', 'VAR_0': 'RecordStore', 'VAR_1': 'operation_RS', 'CLASS_1': 'UIController', 'VAR_2': 'RECORDSTORE_OPERATIONNAME', 'CLASS_2': 'RecordStoreException', 'VAR_3': 'System', 'VAR_4': 'out', 'FUNC_0': 'getNumRecords', 'FUNC_1': 'DefaultRS', 'FUNC_2': 'getMessage', 'FUNC_3': 'closeRS', 'FUNC_4': 'closeRecordStore', 'VAR_5': 'ex', 'CLASS_3': 'ByteArrayOutputStream', 'CLASS_4': 'DataOutputStream', 'FUNC_5': 'writeBoolean', 'VAR_6': 'Setting', 'VAR_7': 'btips', 'FUNC_6': 'writeInt', 'VAR_8': 'resultmax', 'VAR_9': 'approlevel', 'VAR_10': 'dbarray0', 'VAR_11': 'dbarray1', 'VAR_12': 'net0', 'VAR_13': 'net1', 'FUNC_7': 'writeUTF', 'FUNC_8': 'toByteArray', 'FUNC_9': 'addRecord', 'CLASS_5': 'ItemOption', 'VAR_14': 'operitem', 'FUNC_10': 'getapprolevel', 'FUNC_11': 'getdbarray0', 'FUNC_12': 'getdbarray1', 'FUNC_13': 'getnet0', 'FUNC_14': 'getnet1', 'FUNC_15': 'getMachineCode', 'FUNC_16': 'getRegister', 'FUNC_17': 'getRS', 'VAR_15': 'bais', 'CLASS_6': 'DataInputStream', 'VAR_16': 'dis', 'FUNC_18': 'setapprolevel', 'FUNC_19': 'setdbarray1', 'FUNC_20': 'setnet0', 'FUNC_21': 'setMachineCode', 'FUNC_22': 'readUTF', 'FUNC_23': 'setRegister', 'FUNC_24': 'deleteRSb', 'VAR_17': 'id', 'FUNC_25': 'deleteDatabase', 'FUNC_26': 'deleteRecordStore'} | java | OOP | 7.74% |
package com.jennmichelle.theborrowers1.data;
import com.jennmichelle.theborrowers1.models.Borrower;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BorrowerRepository extends CrudRepository<Borrower,Integer> {
}
| package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_4.IMPORT_5;
import IMPORT_6.IMPORT_7.IMPORT_3.IMPORT_8.IMPORT_9;
import IMPORT_6.IMPORT_7.IMPORT_10.IMPORT_11;
@IMPORT_11
public interface CLASS_0 extends IMPORT_9<IMPORT_5,CLASS_1> {
}
| 0.97621 | {'IMPORT_0': 'com', 'IMPORT_1': 'jennmichelle', 'IMPORT_2': 'theborrowers1', 'IMPORT_3': 'data', 'IMPORT_4': 'models', 'IMPORT_5': 'Borrower', 'IMPORT_6': 'org', 'IMPORT_7': 'springframework', 'IMPORT_8': 'repository', 'IMPORT_9': 'CrudRepository', 'IMPORT_10': 'stereotype', 'IMPORT_11': 'Repository', 'CLASS_0': 'BorrowerRepository', 'CLASS_1': 'Integer'} | java | Texto | 96.88% |
/**
* Implementation of an <a href="http://www.w3.org/TR/REC-html40/present/frames.html#h-16.5">inline
* frame</a> component. Must be used with an iframe (<iframe src...) element. The src attribute
* will be generated.
*
* @author Sven Meier
* @author Ralf Ebert
*
*/
public class InlineFrame extends WebMarkupContainer implements IRequestListener
{
private static final long serialVersionUID = 1L;
/** The provider of the page. */
private final IPageProvider pageProvider;
/**
* Constructs an inline frame that instantiates the given Page class when the content of the
* inline frame is requested. The instantiated Page is used to render a response to the user.
*
* @param <C>
*
* @param id
* See Component
* @param c
* Page class
*/
public <C extends Page> InlineFrame(final String id, final Class<C> c)
{
this(id, c, null);
}
/**
* Constructs an inline frame that instantiates the given Page class when the content of the
* inline frame is requested. The instantiated Page is used to render a response to the user.
*
* @param <C>
*
* @param id
* See Component
* @param c
* Page class
* @param params
* Page parameters
*/
public <C extends Page> InlineFrame(final String id, final Class<C> c,
final PageParameters params)
{
this(id, new PageProvider(c, params));
// Ensure that c is a subclass of Page
if (!Page.class.isAssignableFrom(c))
{
throw new IllegalArgumentException("Class " + c + " is not a subclass of Page");
}
}
/**
* This constructor is ideal if a Page object was passed in from a previous Page. Construct an
* inline frame containing the given Page.
*
* @param id
* See component
* @param page
* The page
*/
public InlineFrame(final String id, final Page page)
{
this(id, new PageProvider(page.getPageId(), page.getClass(), page.getRenderCount()));
}
/**
* This constructor is ideal for constructing pages lazily.
*
* Constructs an inline frame which invokes the getPage() method of the IPageLink interface when
* the content of the inline frame is requested. Whatever Page objects is returned by this
* method will be rendered back to the user.
*
* @param id
* See Component
* @param pageProvider
* the provider of the page to be contained in the inline frame if and when the
* content is requested
*/
public InlineFrame(final String id, IPageProvider pageProvider)
{
super(id);
this.pageProvider = pageProvider;
}
/**
* Gets the url to use for this link.
*
* @return The URL that this link links to
*/
protected CharSequence getURL()
{
return urlForListener(new PageParameters());
}
/**
* Handles this frame's tag.
*
* @param tag
* the component tag
* @see org.apache.wicket.Component#onComponentTag(ComponentTag)
*/
@Override
protected void onComponentTag(final ComponentTag tag)
{
checkComponentTag(tag, "iframe");
// Set href to link to this frame's frameRequested method
CharSequence url = getURL();
// generate the src attribute
tag.put("src", url);
super.onComponentTag(tag);
}
@Override
public boolean rendersPage()
{
return false;
}
@Override
public final void onRequest()
{
setResponsePage(pageProvider.getPageInstance());
}
@Override
protected boolean getStatelessHint()
{
/*
* TODO optimization: the inlineframe component does not always have to be stateless.
*
* unfortunately due to current implementation of using a ILinkListener
* callback it has to always be stateful because it can be put inside a ListView item which
* will not be built upon a stateless callback causing a "component at path
* listview:0:iframe not found" error.
*
* eventually variant such as (string, ipagemap, class<? extends Page>) can be made
* stateless because they can generate a bookmarkable url. another advantage of a
* bookmarkable url is that multiple iframes will not block.
*/
return false;
}
} | /**
* Implementation of an <a href="http://www.w3.org/TR/REC-html40/present/frames.html#h-16.5">inline
* frame</a> component. Must be used with an iframe (<iframe src...) element. The src attribute
* will be generated.
*
* @author Sven Meier
* @author Ralf Ebert
*
*/
public class InlineFrame extends CLASS_0 implements IRequestListener
{
private static final long serialVersionUID = 1L;
/** The provider of the page. */
private final IPageProvider pageProvider;
/**
* Constructs an inline frame that instantiates the given Page class when the content of the
* inline frame is requested. The instantiated Page is used to render a response to the user.
*
* @param <C>
*
* @param id
* See Component
* @param c
* Page class
*/
public <C extends Page> InlineFrame(final String id, final Class<C> c)
{
this(id, c, null);
}
/**
* Constructs an inline frame that instantiates the given Page class when the content of the
* inline frame is requested. The instantiated Page is used to render a response to the user.
*
* @param <C>
*
* @param id
* See Component
* @param c
* Page class
* @param params
* Page parameters
*/
public <C extends Page> InlineFrame(final String id, final Class<C> c,
final PageParameters params)
{
this(id, new PageProvider(c, params));
// Ensure that c is a subclass of Page
if (!Page.class.isAssignableFrom(c))
{
throw new IllegalArgumentException("Class " + c + " is not a subclass of Page");
}
}
/**
* This constructor is ideal if a Page object was passed in from a previous Page. Construct an
* inline frame containing the given Page.
*
* @param id
* See component
* @param page
* The page
*/
public InlineFrame(final String id, final Page page)
{
this(id, new PageProvider(page.getPageId(), page.getClass(), page.getRenderCount()));
}
/**
* This constructor is ideal for constructing pages lazily.
*
* Constructs an inline frame which invokes the getPage() method of the IPageLink interface when
* the content of the inline frame is requested. Whatever Page objects is returned by this
* method will be rendered back to the user.
*
* @param id
* See Component
* @param pageProvider
* the provider of the page to be contained in the inline frame if and when the
* content is requested
*/
public InlineFrame(final String id, IPageProvider pageProvider)
{
super(id);
this.pageProvider = pageProvider;
}
/**
* Gets the url to use for this link.
*
* @return The URL that this link links to
*/
protected CLASS_1 getURL()
{
return urlForListener(new PageParameters());
}
/**
* Handles this frame's tag.
*
* @param tag
* the component tag
* @see org.apache.wicket.Component#onComponentTag(ComponentTag)
*/
@Override
protected void onComponentTag(final ComponentTag tag)
{
checkComponentTag(tag, "iframe");
// Set href to link to this frame's frameRequested method
CLASS_1 url = getURL();
// generate the src attribute
tag.put("src", url);
super.onComponentTag(tag);
}
@Override
public boolean rendersPage()
{
return false;
}
@Override
public final void onRequest()
{
FUNC_0(pageProvider.getPageInstance());
}
@Override
protected boolean FUNC_1()
{
/*
* TODO optimization: the inlineframe component does not always have to be stateless.
*
* unfortunately due to current implementation of using a ILinkListener
* callback it has to always be stateful because it can be put inside a ListView item which
* will not be built upon a stateless callback causing a "component at path
* listview:0:iframe not found" error.
*
* eventually variant such as (string, ipagemap, class<? extends Page>) can be made
* stateless because they can generate a bookmarkable url. another advantage of a
* bookmarkable url is that multiple iframes will not block.
*/
return false;
}
} | 0.157584 | {'CLASS_0': 'WebMarkupContainer', 'CLASS_1': 'CharSequence', 'FUNC_0': 'setResponsePage', 'FUNC_1': 'getStatelessHint'} | java | Hibrido | 32.08% |
/**
* Created by 17osullivand on 11/27/16.
*/
@Autonomous(name = "Testing: FIRE BALLS ONLY", group = "Autonomous")
public class FireBallUpdate extends UpdateThread {
@Override
public void setGodThread() {
godThread = FireBallsGodThread.class;
}
} | /**
* Created by 17osullivand on 11/27/16.
*/
@Autonomous(name = "Testing: FIRE BALLS ONLY", VAR_0 = "Autonomous")
public class FireBallUpdate extends UpdateThread {
@Override
public void setGodThread() {
godThread = FireBallsGodThread.class;
}
} | 0.146201 | {'VAR_0': 'group'} | java | Hibrido | 100.00% |
/** Supply a dataset for matching to an attached external data source */
private void externalStorage(Id datasourceId, DatasetGraph dsg) {
if ( !zone.exists(datasourceId) )
throw new DeltaConfigException("Can't add external storage: data source not attached to this zone: " + datasourceId);
DataState dataState = zone.get(datasourceId);
if ( !LocalStorageType.EXTERNAL.equals(dataState.getStorageType()) ) {
throw new DeltaConfigException("Can't add external storage: data source is not 'external': " + datasourceId);
}
zone.externalStorage(datasourceId, dsg);
} | /** Supply a dataset for matching to an attached external data source */
private void externalStorage(CLASS_0 VAR_0, DatasetGraph dsg) {
if ( !zone.exists(VAR_0) )
throw new CLASS_1("Can't add external storage: data source not attached to this zone: " + VAR_0);
DataState dataState = zone.get(VAR_0);
if ( !LocalStorageType.EXTERNAL.equals(dataState.FUNC_0()) ) {
throw new CLASS_1("Can't add external storage: data source is not 'external': " + VAR_0);
}
zone.externalStorage(VAR_0, dsg);
} | 0.301009 | {'CLASS_0': 'Id', 'VAR_0': 'datasourceId', 'CLASS_1': 'DeltaConfigException', 'FUNC_0': 'getStorageType'} | java | Procedural | 37.68% |
package relicstats.patches.relics;
import com.badlogic.gdx.math.MathUtils;
import com.evacipated.cardcrawl.modthespire.lib.*;
import com.evacipated.cardcrawl.modthespire.patcher.PatchingException;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.relics.Courier;
import com.megacrit.cardcrawl.relics.MembershipCard;
import com.megacrit.cardcrawl.shop.ShopScreen;
import com.megacrit.cardcrawl.shop.StorePotion;
import com.megacrit.cardcrawl.shop.StoreRelic;
import javassist.CannotCompileException;
import javassist.CtBehavior;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import relicstats.RelicStats;
import relicstats.StatsInfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class MembershipCardInfo extends StatsInfo {
private static final Logger logger = LogManager.getLogger(MembershipCardInfo.class.getName());
private static int discount;
private static String statId = getLocId(MembershipCard.ID);
private static String[] description = CardCrawlGame.languagePack.getUIString(statId).TEXT;
private static Map<AbstractCard, Integer> cardDiscounts = new HashMap<>();
private static Map<StoreRelic, Integer> relicDiscounts = new HashMap<>();
private static Map<StorePotion, Integer> potionDiscounts = new HashMap<>();
@Override
public String getStatsDescription() {
String addendum = "";
if ((AbstractDungeon.player == null) || (!CardCrawlGame.isInARun()) || (AbstractDungeon.player.hasRelic(Courier.ID) && AbstractDungeon.player.hasRelic(MembershipCard.ID))) {
addendum = description[1];
}
return String.format("%s%d%s", description[0], discount, addendum);
}
@Override
public void resetStats() {
discount = 0;
}
@Override
public JsonElement onSaveRaw() {
Gson gson = new Gson();
return gson.toJsonTree(discount);
}
@Override
public void onLoadRaw(JsonElement jsonElement) {
if (jsonElement != null) {
discount = jsonElement.getAsInt();
} else {
resetStats();
}
}
@SpirePatch(
clz = ShopScreen.class,
method = "init"
)
public static class ShopScreenInitPatch {
@SpirePrefixPatch
public static void patch(ShopScreen _instance, ArrayList<AbstractCard> coloredCards, ArrayList<AbstractCard> colorlessCards) {
cardDiscounts = new HashMap<>();
relicDiscounts = new HashMap<>();
potionDiscounts = new HashMap<>();
}
}
@SpirePatch(
clz = ShopScreen.class,
method = "applyDiscount"
)
public static class ShopScreenCardPricePatch {
@SpireInsertPatch(
locator=RelicLocator.class,
localvars={"r"}
)
public static void relicPricePatch(ShopScreen _instance, float multiplier, boolean affectPurge, StoreRelic r) {
if (multiplier >= 1.0) {
return;
}
int currentDiscount = relicDiscounts.getOrDefault(r, 0);
currentDiscount += (r.price - MathUtils.round(r.price * multiplier));
relicDiscounts.put(r, currentDiscount);
}
private static class RelicLocator extends SpireInsertLocator {
public int[] Locate(CtBehavior ctMethodToPatch) throws CannotCompileException, PatchingException {
Matcher matcher = new Matcher.MethodCallMatcher(MathUtils.class, "round");
return LineFinder.findInOrder(ctMethodToPatch, new ArrayList<Matcher>(), matcher);
}
}
@SpireInsertPatch(
locator=PotionLocator.class,
localvars={"p"}
)
public static void potionPricePatch(ShopScreen _instance, float multiplier, boolean affectPurge, StorePotion p) {
if (multiplier >= 1.0) {
return;
}
int currentDiscount = potionDiscounts.getOrDefault(p, 0);
currentDiscount += (p.price - MathUtils.round(p.price * multiplier));
potionDiscounts.put(p, currentDiscount);
}
private static class PotionLocator extends SpireInsertLocator {
public int[] Locate(CtBehavior ctMethodToPatch) throws CannotCompileException, PatchingException {
Matcher matcher = new Matcher.FieldAccessMatcher(StorePotion.class, "price");
return LineFinder.findInOrder(ctMethodToPatch, new ArrayList<Matcher>(), matcher);
}
}
@SpireInsertPatch(
locator=CardLocator.class,
localvars={"c"}
)
public static void cardPricePatch(ShopScreen _instance, float multiplier, boolean affectPurge, AbstractCard c) {
if (multiplier >= 1.0) {
return;
}
int currentDiscount = cardDiscounts.getOrDefault(c, 0);
currentDiscount += (c.price - MathUtils.round(c.price * multiplier));
cardDiscounts.put(c, currentDiscount);
}
private static class CardLocator extends SpireInsertLocator {
public int[] Locate(CtBehavior ctMethodToPatch) throws CannotCompileException, PatchingException {
Matcher matcher = new Matcher.MethodCallMatcher(MathUtils.class, "round");
int[] matches = LineFinder.findAllInOrder(ctMethodToPatch, new ArrayList<Matcher>(), matcher);
return Arrays.copyOfRange(matches, 2, 4);
}
}
}
@SpirePatch(
clz = ShopScreen.class,
method = "purchaseCard"
)
public static class ShopScreenCardPurchasePatch {
@SpireInsertPatch(
locator=Locator.class
)
public static void insert(ShopScreen _instance, AbstractCard hoveredCard) {
if (cardDiscounts.containsKey(hoveredCard)) {
int cardDiscount = cardDiscounts.remove(hoveredCard);
discount += cardDiscount;
} else {
logger.error("Could not find discount for purchased card.");
}
}
private static class Locator extends SpireInsertLocator {
public int[] Locate(CtBehavior ctMethodToPatch) throws CannotCompileException, PatchingException {
Matcher matcher = new Matcher.MethodCallMatcher(AbstractPlayer.class, "loseGold");
return LineFinder.findInOrder(ctMethodToPatch, new ArrayList<Matcher>(), matcher);
}
}
}
@SpirePatch(
clz = StoreRelic.class,
method = "purchaseRelic"
)
public static class RelicPurchasePatch {
@SpireInsertPatch(
locator= Locator.class
)
public static void insert(StoreRelic _instance) {
if (relicDiscounts.containsKey(_instance)) {
int relicDiscount = relicDiscounts.remove(_instance);
discount += relicDiscount;
} else {
logger.error("Could not find discount for purchased relic.");
}
}
private static class Locator extends SpireInsertLocator {
public int[] Locate(CtBehavior ctMethodToPatch) throws CannotCompileException, PatchingException {
Matcher matcher = new Matcher.MethodCallMatcher(AbstractPlayer.class, "loseGold");
return LineFinder.findInOrder(ctMethodToPatch, new ArrayList<Matcher>(), matcher);
}
}
}
@SpirePatch(
clz = StorePotion.class,
method = "purchasePotion"
)
public static class PotionPurchasePatch {
@SpireInsertPatch(
locator= Locator.class
)
public static void insert(StorePotion _instance) {
if (potionDiscounts.containsKey(_instance)) {
int potionDiscount = potionDiscounts.remove(_instance);
discount += potionDiscount;
} else {
logger.error("Could not find discount for purchased potion.");
}
}
private static class Locator extends SpireInsertLocator {
public int[] Locate(CtBehavior ctMethodToPatch) throws CannotCompileException, PatchingException {
Matcher matcher = new Matcher.MethodCallMatcher(AbstractPlayer.class, "loseGold");
return LineFinder.findInOrder(ctMethodToPatch, new ArrayList<Matcher>(), matcher);
}
}
}
@SpirePatch(
clz = ShopScreen.class,
method = "getNewPrice",
paramtypez = {StoreRelic.class}
)
public static class RelicRestockPatch {
private static int initialPrice;
@SpireInsertPatch(
locator= Locator.class,
localvars = {"retVal"}
)
public static void insert(ShopScreen _instance, StoreRelic r, int retVal) {
initialPrice = retVal;
}
private static class Locator extends SpireInsertLocator {
public int[] Locate(CtBehavior ctMethodToPatch) throws CannotCompileException, PatchingException {
Matcher matcher = new Matcher.MethodCallMatcher(AbstractPlayer.class, "hasRelic");
return LineFinder.findInOrder(ctMethodToPatch, new ArrayList<Matcher>(), matcher);
}
}
@SpirePostfixPatch
public static void postfix(ShopScreen _instance, StoreRelic r) {
int relicDiscount = initialPrice - r.price;
relicDiscounts.put(r, relicDiscount);
}
}
@SpirePatch(
clz = ShopScreen.class,
method = "getNewPrice",
paramtypez = {StorePotion.class}
)
public static class PotionRestockPatch {
private static int initialPrice;
@SpireInsertPatch(
locator= Locator.class,
localvars = {"retVal"}
)
public static void insert(ShopScreen _instance, StorePotion p, int retVal) {
initialPrice = retVal;
}
private static class Locator extends SpireInsertLocator {
public int[] Locate(CtBehavior ctMethodToPatch) throws CannotCompileException, PatchingException {
Matcher matcher = new Matcher.MethodCallMatcher(AbstractPlayer.class, "hasRelic");
return LineFinder.findInOrder(ctMethodToPatch, new ArrayList<Matcher>(), matcher);
}
}
@SpirePostfixPatch
public static void postfix(ShopScreen _instance, StorePotion p) {
int potionDiscount = initialPrice - p.price;
potionDiscounts.put(p, potionDiscount);
}
}
@SpirePatch(
clz = ShopScreen.class,
method = "setPrice"
)
public static class CardRestockPatch {
private static int initialPrice;
@SpireInsertPatch(
locator= Locator.class,
localvars = {"tmpPrice"}
)
public static void insert(ShopScreen _instance, AbstractCard c, float tmpPrice) {
initialPrice = (int)tmpPrice;
}
private static class Locator extends SpireInsertLocator {
public int[] Locate(CtBehavior ctMethodToPatch) throws CannotCompileException, PatchingException {
Matcher matcher = new Matcher.MethodCallMatcher(AbstractPlayer.class, "hasRelic");
return LineFinder.findInOrder(ctMethodToPatch, new ArrayList<Matcher>(), matcher);
}
}
@SpirePostfixPatch
public static void postfix(ShopScreen _instance, AbstractCard c) {
int cardDiscount = initialPrice - c.price;
cardDiscounts.put(c, cardDiscount);
}
}
@SpirePatch(
clz = ShopScreen.class,
method = "purgeCard"
)
public static class PurgeCardPatch {
@SpirePrefixPatch
public static void patch() {
float discountedCost = (float)ShopScreen.purgeCost;
if (AbstractDungeon.player.hasRelic(MembershipCard.ID)) {
discountedCost *= 0.5;
} else if (AbstractDungeon.player.hasRelic(Courier.ID)) {
// This is else if because the base game is bugged to only apply membership card here if you own both
discountedCost *= 0.8;
}
discountedCost = MathUtils.round(discountedCost);
discount += ShopScreen.purgeCost - discountedCost;
}
}
}
| package relicstats.patches.IMPORT_0;
import com.badlogic.gdx.math.IMPORT_1;
import com.evacipated.IMPORT_2.modthespire.IMPORT_3.*;
import com.evacipated.IMPORT_2.modthespire.patcher.IMPORT_4;
import com.google.gson.IMPORT_5;
import com.google.gson.JsonElement;
import com.IMPORT_6.IMPORT_2.IMPORT_7.IMPORT_8;
import com.IMPORT_6.IMPORT_2.characters.AbstractPlayer;
import com.IMPORT_6.IMPORT_2.core.IMPORT_9;
import com.IMPORT_6.IMPORT_2.IMPORT_10.IMPORT_11;
import com.IMPORT_6.IMPORT_2.IMPORT_0.Courier;
import com.IMPORT_6.IMPORT_2.IMPORT_0.IMPORT_12;
import com.IMPORT_6.IMPORT_2.shop.ShopScreen;
import com.IMPORT_6.IMPORT_2.shop.IMPORT_13;
import com.IMPORT_6.IMPORT_2.shop.StoreRelic;
import javassist.CannotCompileException;
import javassist.IMPORT_14;
import IMPORT_15.IMPORT_16.logging.log4j.IMPORT_17;
import IMPORT_15.IMPORT_16.logging.log4j.Logger;
import relicstats.IMPORT_18;
import relicstats.StatsInfo;
import java.util.ArrayList;
import java.util.IMPORT_19;
import java.util.HashMap;
import java.util.Map;
public class MembershipCardInfo extends StatsInfo {
private static final Logger VAR_0 = IMPORT_17.FUNC_0(MembershipCardInfo.class.FUNC_1());
private static int VAR_1;
private static String statId = getLocId(IMPORT_12.ID);
private static String[] VAR_2 = IMPORT_9.languagePack.getUIString(statId).VAR_3;
private static Map<IMPORT_8, CLASS_0> cardDiscounts = new HashMap<>();
private static Map<StoreRelic, CLASS_0> relicDiscounts = new HashMap<>();
private static Map<IMPORT_13, CLASS_0> potionDiscounts = new HashMap<>();
@VAR_4
public String FUNC_2() {
String VAR_5 = "";
if ((IMPORT_11.VAR_6 == null) || (!IMPORT_9.FUNC_3()) || (IMPORT_11.VAR_6.FUNC_4(Courier.ID) && IMPORT_11.VAR_6.FUNC_4(IMPORT_12.ID))) {
VAR_5 = VAR_2[1];
}
return String.FUNC_5("%s%d%s", VAR_2[0], VAR_1, VAR_5);
}
@VAR_4
public void FUNC_6() {
VAR_1 = 0;
}
@VAR_4
public JsonElement onSaveRaw() {
IMPORT_5 gson = new IMPORT_5();
return gson.FUNC_7(VAR_1);
}
@VAR_4
public void onLoadRaw(JsonElement jsonElement) {
if (jsonElement != null) {
VAR_1 = jsonElement.FUNC_8();
} else {
FUNC_6();
}
}
@VAR_7(
VAR_8 = ShopScreen.class,
method = "init"
)
public static class ShopScreenInitPatch {
@VAR_9
public static void patch(ShopScreen VAR_10, ArrayList<IMPORT_8> VAR_11, ArrayList<IMPORT_8> VAR_12) {
cardDiscounts = new HashMap<>();
relicDiscounts = new HashMap<>();
potionDiscounts = new HashMap<>();
}
}
@VAR_7(
VAR_8 = ShopScreen.class,
method = "applyDiscount"
)
public static class ShopScreenCardPricePatch {
@SpireInsertPatch(
VAR_13=CLASS_1.class,
VAR_14={"r"}
)
public static void relicPricePatch(ShopScreen VAR_10, float multiplier, boolean VAR_15, StoreRelic r) {
if (multiplier >= 1.0) {
return;
}
int VAR_16 = relicDiscounts.getOrDefault(r, 0);
VAR_16 += (r.price - IMPORT_1.round(r.price * multiplier));
relicDiscounts.FUNC_9(r, VAR_16);
}
private static class CLASS_1 extends SpireInsertLocator {
public int[] FUNC_10(IMPORT_14 VAR_17) throws CannotCompileException, IMPORT_4 {
CLASS_2 matcher = new CLASS_2.MethodCallMatcher(IMPORT_1.class, "round");
return VAR_18.findInOrder(VAR_17, new ArrayList<CLASS_2>(), matcher);
}
}
@SpireInsertPatch(
VAR_13=CLASS_3.class,
VAR_14={"p"}
)
public static void potionPricePatch(ShopScreen VAR_10, float multiplier, boolean VAR_15, IMPORT_13 VAR_19) {
if (multiplier >= 1.0) {
return;
}
int VAR_16 = potionDiscounts.getOrDefault(VAR_19, 0);
VAR_16 += (VAR_19.price - IMPORT_1.round(VAR_19.price * multiplier));
potionDiscounts.FUNC_9(VAR_19, VAR_16);
}
private static class CLASS_3 extends SpireInsertLocator {
public int[] FUNC_10(IMPORT_14 VAR_17) throws CannotCompileException, IMPORT_4 {
CLASS_2 matcher = new CLASS_2.FieldAccessMatcher(IMPORT_13.class, "price");
return VAR_18.findInOrder(VAR_17, new ArrayList<CLASS_2>(), matcher);
}
}
@SpireInsertPatch(
VAR_13=CardLocator.class,
VAR_14={"c"}
)
public static void FUNC_11(ShopScreen VAR_10, float multiplier, boolean VAR_15, IMPORT_8 VAR_20) {
if (multiplier >= 1.0) {
return;
}
int VAR_16 = cardDiscounts.getOrDefault(VAR_20, 0);
VAR_16 += (VAR_20.price - IMPORT_1.round(VAR_20.price * multiplier));
cardDiscounts.FUNC_9(VAR_20, VAR_16);
}
private static class CardLocator extends SpireInsertLocator {
public int[] FUNC_10(IMPORT_14 VAR_17) throws CannotCompileException, IMPORT_4 {
CLASS_2 matcher = new CLASS_2.MethodCallMatcher(IMPORT_1.class, "round");
int[] matches = VAR_18.FUNC_12(VAR_17, new ArrayList<CLASS_2>(), matcher);
return IMPORT_19.copyOfRange(matches, 2, 4);
}
}
}
@VAR_7(
VAR_8 = ShopScreen.class,
method = "purchaseCard"
)
public static class ShopScreenCardPurchasePatch {
@SpireInsertPatch(
VAR_13=CLASS_4.class
)
public static void FUNC_13(ShopScreen VAR_10, IMPORT_8 VAR_21) {
if (cardDiscounts.containsKey(VAR_21)) {
int VAR_22 = cardDiscounts.FUNC_14(VAR_21);
VAR_1 += VAR_22;
} else {
VAR_0.FUNC_15("Could not find discount for purchased card.");
}
}
private static class CLASS_4 extends SpireInsertLocator {
public int[] FUNC_10(IMPORT_14 VAR_17) throws CannotCompileException, IMPORT_4 {
CLASS_2 matcher = new CLASS_2.MethodCallMatcher(AbstractPlayer.class, "loseGold");
return VAR_18.findInOrder(VAR_17, new ArrayList<CLASS_2>(), matcher);
}
}
}
@VAR_7(
VAR_8 = StoreRelic.class,
method = "purchaseRelic"
)
public static class RelicPurchasePatch {
@SpireInsertPatch(
VAR_13= CLASS_4.class
)
public static void FUNC_13(StoreRelic VAR_10) {
if (relicDiscounts.containsKey(VAR_10)) {
int VAR_23 = relicDiscounts.FUNC_14(VAR_10);
VAR_1 += VAR_23;
} else {
VAR_0.FUNC_15("Could not find discount for purchased relic.");
}
}
private static class CLASS_4 extends SpireInsertLocator {
public int[] FUNC_10(IMPORT_14 VAR_17) throws CannotCompileException, IMPORT_4 {
CLASS_2 matcher = new CLASS_2.MethodCallMatcher(AbstractPlayer.class, "loseGold");
return VAR_18.findInOrder(VAR_17, new ArrayList<CLASS_2>(), matcher);
}
}
}
@VAR_7(
VAR_8 = IMPORT_13.class,
method = "purchasePotion"
)
public static class CLASS_5 {
@SpireInsertPatch(
VAR_13= CLASS_4.class
)
public static void FUNC_13(IMPORT_13 VAR_10) {
if (potionDiscounts.containsKey(VAR_10)) {
int VAR_24 = potionDiscounts.FUNC_14(VAR_10);
VAR_1 += VAR_24;
} else {
VAR_0.FUNC_15("Could not find discount for purchased potion.");
}
}
private static class CLASS_4 extends SpireInsertLocator {
public int[] FUNC_10(IMPORT_14 VAR_17) throws CannotCompileException, IMPORT_4 {
CLASS_2 matcher = new CLASS_2.MethodCallMatcher(AbstractPlayer.class, "loseGold");
return VAR_18.findInOrder(VAR_17, new ArrayList<CLASS_2>(), matcher);
}
}
}
@VAR_7(
VAR_8 = ShopScreen.class,
method = "getNewPrice",
paramtypez = {StoreRelic.class}
)
public static class RelicRestockPatch {
private static int VAR_25;
@SpireInsertPatch(
VAR_13= CLASS_4.class,
VAR_14 = {"retVal"}
)
public static void FUNC_13(ShopScreen VAR_10, StoreRelic r, int VAR_26) {
VAR_25 = VAR_26;
}
private static class CLASS_4 extends SpireInsertLocator {
public int[] FUNC_10(IMPORT_14 VAR_17) throws CannotCompileException, IMPORT_4 {
CLASS_2 matcher = new CLASS_2.MethodCallMatcher(AbstractPlayer.class, "hasRelic");
return VAR_18.findInOrder(VAR_17, new ArrayList<CLASS_2>(), matcher);
}
}
@VAR_27
public static void FUNC_16(ShopScreen VAR_10, StoreRelic r) {
int VAR_23 = VAR_25 - r.price;
relicDiscounts.FUNC_9(r, VAR_23);
}
}
@VAR_7(
VAR_8 = ShopScreen.class,
method = "getNewPrice",
paramtypez = {IMPORT_13.class}
)
public static class PotionRestockPatch {
private static int VAR_25;
@SpireInsertPatch(
VAR_13= CLASS_4.class,
VAR_14 = {"retVal"}
)
public static void FUNC_13(ShopScreen VAR_10, IMPORT_13 VAR_19, int VAR_26) {
VAR_25 = VAR_26;
}
private static class CLASS_4 extends SpireInsertLocator {
public int[] FUNC_10(IMPORT_14 VAR_17) throws CannotCompileException, IMPORT_4 {
CLASS_2 matcher = new CLASS_2.MethodCallMatcher(AbstractPlayer.class, "hasRelic");
return VAR_18.findInOrder(VAR_17, new ArrayList<CLASS_2>(), matcher);
}
}
@VAR_27
public static void FUNC_16(ShopScreen VAR_10, IMPORT_13 VAR_19) {
int VAR_24 = VAR_25 - VAR_19.price;
potionDiscounts.FUNC_9(VAR_19, VAR_24);
}
}
@VAR_7(
VAR_8 = ShopScreen.class,
method = "setPrice"
)
public static class CardRestockPatch {
private static int VAR_25;
@SpireInsertPatch(
VAR_13= CLASS_4.class,
VAR_14 = {"tmpPrice"}
)
public static void FUNC_13(ShopScreen VAR_10, IMPORT_8 VAR_20, float VAR_28) {
VAR_25 = (int)VAR_28;
}
private static class CLASS_4 extends SpireInsertLocator {
public int[] FUNC_10(IMPORT_14 VAR_17) throws CannotCompileException, IMPORT_4 {
CLASS_2 matcher = new CLASS_2.MethodCallMatcher(AbstractPlayer.class, "hasRelic");
return VAR_18.findInOrder(VAR_17, new ArrayList<CLASS_2>(), matcher);
}
}
@VAR_27
public static void FUNC_16(ShopScreen VAR_10, IMPORT_8 VAR_20) {
int VAR_22 = VAR_25 - VAR_20.price;
cardDiscounts.FUNC_9(VAR_20, VAR_22);
}
}
@VAR_7(
VAR_8 = ShopScreen.class,
method = "purgeCard"
)
public static class PurgeCardPatch {
@VAR_9
public static void patch() {
float discountedCost = (float)ShopScreen.VAR_29;
if (IMPORT_11.VAR_6.FUNC_4(IMPORT_12.ID)) {
discountedCost *= 0.5;
} else if (IMPORT_11.VAR_6.FUNC_4(Courier.ID)) {
// This is else if because the base game is bugged to only apply membership card here if you own both
discountedCost *= 0.8;
}
discountedCost = IMPORT_1.round(discountedCost);
VAR_1 += ShopScreen.VAR_29 - discountedCost;
}
}
}
| 0.51717 | {'IMPORT_0': 'relics', 'IMPORT_1': 'MathUtils', 'IMPORT_2': 'cardcrawl', 'IMPORT_3': 'lib', 'IMPORT_4': 'PatchingException', 'IMPORT_5': 'Gson', 'IMPORT_6': 'megacrit', 'IMPORT_7': 'cards', 'IMPORT_8': 'AbstractCard', 'IMPORT_9': 'CardCrawlGame', 'IMPORT_10': 'dungeons', 'IMPORT_11': 'AbstractDungeon', 'IMPORT_12': 'MembershipCard', 'IMPORT_13': 'StorePotion', 'IMPORT_14': 'CtBehavior', 'IMPORT_15': 'org', 'IMPORT_16': 'apache', 'IMPORT_17': 'LogManager', 'IMPORT_18': 'RelicStats', 'IMPORT_19': 'Arrays', 'VAR_0': 'logger', 'FUNC_0': 'getLogger', 'FUNC_1': 'getName', 'VAR_1': 'discount', 'VAR_2': 'description', 'VAR_3': 'TEXT', 'CLASS_0': 'Integer', 'VAR_4': 'Override', 'FUNC_2': 'getStatsDescription', 'VAR_5': 'addendum', 'VAR_6': 'player', 'FUNC_3': 'isInARun', 'FUNC_4': 'hasRelic', 'FUNC_5': 'format', 'FUNC_6': 'resetStats', 'FUNC_7': 'toJsonTree', 'FUNC_8': 'getAsInt', 'VAR_7': 'SpirePatch', 'VAR_8': 'clz', 'VAR_9': 'SpirePrefixPatch', 'VAR_10': '_instance', 'VAR_11': 'coloredCards', 'VAR_12': 'colorlessCards', 'VAR_13': 'locator', 'CLASS_1': 'RelicLocator', 'VAR_14': 'localvars', 'VAR_15': 'affectPurge', 'VAR_16': 'currentDiscount', 'FUNC_9': 'put', 'FUNC_10': 'Locate', 'VAR_17': 'ctMethodToPatch', 'CLASS_2': 'Matcher', 'VAR_18': 'LineFinder', 'CLASS_3': 'PotionLocator', 'VAR_19': 'p', 'FUNC_11': 'cardPricePatch', 'VAR_20': 'c', 'FUNC_12': 'findAllInOrder', 'CLASS_4': 'Locator', 'FUNC_13': 'insert', 'VAR_21': 'hoveredCard', 'VAR_22': 'cardDiscount', 'FUNC_14': 'remove', 'FUNC_15': 'error', 'VAR_23': 'relicDiscount', 'CLASS_5': 'PotionPurchasePatch', 'VAR_24': 'potionDiscount', 'VAR_25': 'initialPrice', 'VAR_26': 'retVal', 'VAR_27': 'SpirePostfixPatch', 'FUNC_16': 'postfix', 'VAR_28': 'tmpPrice', 'VAR_29': 'purgeCost'} | java | OOP | 10.36% |
/**
* Adds the given parameter and all additional {@link Parameter parameter}
* to the action in construction. Any {@code null} values are filtered.
*
* @param p the first parameter to add
* @param add additional parameters to add
* @return this action factory
* @see #parameter(java.lang.String, java.lang.Class)
*/
public ActionFactory parameter(Parameter p, Parameter... add)
{
if (p != null)
{
currentParameters.add(p);
}
if (add != null)
{
currentParameters
.addAll(Arrays.asList(add).stream().filter(Objects::nonNull).collect(
Collectors.toList()));
}
return this;
} | /**
* Adds the given parameter and all additional {@link Parameter parameter}
* to the action in construction. Any {@code null} values are filtered.
*
* @param p the first parameter to add
* @param add additional parameters to add
* @return this action factory
* @see #parameter(java.lang.String, java.lang.Class)
*/
public ActionFactory FUNC_0(CLASS_0 VAR_0, CLASS_0... add)
{
if (VAR_0 != null)
{
currentParameters.add(VAR_0);
}
if (add != null)
{
currentParameters
.addAll(Arrays.FUNC_1(add).stream().filter(Objects::nonNull).collect(
Collectors.toList()));
}
return this;
} | 0.309563 | {'FUNC_0': 'parameter', 'CLASS_0': 'Parameter', 'VAR_0': 'p', 'FUNC_1': 'asList'} | java | Texto | 7.41% |
package ir.areka.analyzer.lucene;
import java.io.IOException;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.fa.PersianAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
public class FarsiStopWordTokenFilter extends TokenFilter {
private CharTermAttribute charTermAtt;
private PositionIncrementAttribute posIncrementAtt;
protected FarsiStopWordTokenFilter(TokenStream input) {
super(input);
charTermAtt = addAttribute(CharTermAttribute.class);
posIncrementAtt = addAttribute(PositionIncrementAttribute.class);
}
@Override
public boolean incrementToken() throws IOException {
int extraIncrement = 0;
boolean returnValue = false;
while (input.incrementToken()) {
if (PersianAnalyzer.DEFAULT_STOPWORD_FILE.contains(charTermAtt.toString())) {
extraIncrement++;// filter this word
continue;
}
returnValue = true;
break;
}
if (extraIncrement > 0)
posIncrementAtt.setPositionIncrement(posIncrementAtt.getPositionIncrement() + extraIncrement);
return returnValue;
}
}
| package IMPORT_0.areka.IMPORT_1.IMPORT_2;
import IMPORT_3.IMPORT_4.IOException;
import IMPORT_5.IMPORT_6.IMPORT_2.analysis.IMPORT_7;
import IMPORT_5.IMPORT_6.IMPORT_2.analysis.IMPORT_8;
import IMPORT_5.IMPORT_6.IMPORT_2.analysis.IMPORT_9.PersianAnalyzer;
import IMPORT_5.IMPORT_6.IMPORT_2.analysis.IMPORT_10.IMPORT_11;
import IMPORT_5.IMPORT_6.IMPORT_2.analysis.IMPORT_10.IMPORT_12;
public class CLASS_0 extends IMPORT_7 {
private IMPORT_11 VAR_0;
private IMPORT_12 VAR_1;
protected CLASS_0(IMPORT_8 input) {
super(input);
VAR_0 = FUNC_0(IMPORT_11.class);
VAR_1 = FUNC_0(IMPORT_12.class);
}
@VAR_2
public boolean FUNC_1() throws IOException {
int extraIncrement = 0;
boolean VAR_3 = false;
while (input.FUNC_1()) {
if (PersianAnalyzer.VAR_4.FUNC_2(VAR_0.FUNC_3())) {
extraIncrement++;// filter this word
continue;
}
VAR_3 = true;
break;
}
if (extraIncrement > 0)
VAR_1.FUNC_4(VAR_1.getPositionIncrement() + extraIncrement);
return VAR_3;
}
}
| 0.713238 | {'IMPORT_0': 'ir', 'IMPORT_1': 'analyzer', 'IMPORT_2': 'lucene', 'IMPORT_3': 'java', 'IMPORT_4': 'io', 'IMPORT_5': 'org', 'IMPORT_6': 'apache', 'IMPORT_7': 'TokenFilter', 'IMPORT_8': 'TokenStream', 'IMPORT_9': 'fa', 'IMPORT_10': 'tokenattributes', 'IMPORT_11': 'CharTermAttribute', 'IMPORT_12': 'PositionIncrementAttribute', 'CLASS_0': 'FarsiStopWordTokenFilter', 'VAR_0': 'charTermAtt', 'VAR_1': 'posIncrementAtt', 'FUNC_0': 'addAttribute', 'VAR_2': 'Override', 'FUNC_1': 'incrementToken', 'VAR_3': 'returnValue', 'VAR_4': 'DEFAULT_STOPWORD_FILE', 'FUNC_2': 'contains', 'FUNC_3': 'toString', 'FUNC_4': 'setPositionIncrement'} | java | OOP | 50.00% |
package com.example.hotpot;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Spinner;
public class Uyegiris extends Activity {
Button buttungir;
Spinner spin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uyegiris);
buttungir = (Button) findViewById(R.id.btnLogin);
spin = (Spinner) findViewById(R.id.spinner1);
addListenerOnSpinnerItemSelection();
}
public void addListenerOnSpinnerItemSelection() {
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
if (pos == 1) {
buttungir.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Uyegiris.this,
MainActivitySatici.class);
startActivity(i);
}
});
} else if (pos == 0) {
buttungir.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Uyegiris.this,
MainActivityUye.class);
startActivity(i);
}
});
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
| package IMPORT_0.IMPORT_1.IMPORT_2;
import android.app.Activity;
import android.IMPORT_3.Intent;
import android.IMPORT_4.Bundle;
import android.IMPORT_5.IMPORT_6;
import android.IMPORT_5.IMPORT_6.OnClickListener;
import android.widget.IMPORT_7;
import android.widget.IMPORT_7.OnItemSelectedListener;
import android.widget.IMPORT_8;
import android.widget.Spinner;
public class CLASS_0 extends Activity {
IMPORT_8 VAR_1;
Spinner spin;
@VAR_2
protected void FUNC_0(Bundle VAR_3) {
super.FUNC_0(VAR_3);
FUNC_1(R.layout.VAR_4);
VAR_1 = (IMPORT_8) findViewById(R.id.VAR_5);
spin = (Spinner) findViewById(R.id.spinner1);
FUNC_2();
}
public void FUNC_2() {
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
@VAR_2
public void onItemSelected(IMPORT_7<?> parent, IMPORT_6 IMPORT_5,
int VAR_6, long id) {
if (VAR_6 == 1) {
VAR_1.FUNC_3(new OnClickListener() {
@VAR_2
public void onClick(IMPORT_6 v) {
Intent i = new Intent(VAR_0.this,
CLASS_1.class);
FUNC_4(i);
}
});
} else if (VAR_6 == 0) {
VAR_1.FUNC_3(new OnClickListener() {
@VAR_2
public void onClick(IMPORT_6 v) {
Intent i = new Intent(VAR_0.this,
CLASS_2.class);
FUNC_4(i);
}
});
}
}
@VAR_2
public void FUNC_5(IMPORT_7<?> parent) {
}
});
}
}
| 0.499181 | {'IMPORT_0': 'com', 'IMPORT_1': 'example', 'IMPORT_2': 'hotpot', 'IMPORT_3': 'content', 'IMPORT_4': 'os', 'IMPORT_5': 'view', 'IMPORT_6': 'View', 'IMPORT_7': 'AdapterView', 'IMPORT_8': 'Button', 'CLASS_0': 'Uyegiris', 'VAR_0': 'Uyegiris', 'VAR_1': 'buttungir', 'VAR_2': 'Override', 'FUNC_0': 'onCreate', 'VAR_3': 'savedInstanceState', 'FUNC_1': 'setContentView', 'VAR_4': 'activity_uyegiris', 'VAR_5': 'btnLogin', 'FUNC_2': 'addListenerOnSpinnerItemSelection', 'VAR_6': 'pos', 'FUNC_3': 'setOnClickListener', 'CLASS_1': 'MainActivitySatici', 'FUNC_4': 'startActivity', 'CLASS_2': 'MainActivityUye', 'FUNC_5': 'onNothingSelected'} | java | OOP | 48.87% |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.