method2testcases
stringlengths 118
3.08k
|
---|
### Question:
Fn { public static Map<String, Object> queryParams(Object... params){ Map<String, Object> result = new HashMap(); int c = 0; Object key = null; for (Object param:params){ c++; if (c%2 != 0){ key = param; } else if (key != null && !key.toString().isEmpty()){ result.put(key.toString(), param); } } return result; } private Fn(); static boolean inList(String obj, String... list); static boolean inList(Integer obj, int... list); static T iif(Boolean condition, T value1, T value2); static Integer findInMatrix(Object[] matrix, Object search); static Integer findInMatrix(String[] matrix, String search, Boolean caseSensitive); static Boolean toLogical(Object value); static T nvl(T value, T alternateValue); static String bytesToHex(byte[] bytes); static byte[] hexToByte(String hexText); static byte[] base64ToBytes(String encrypted64); static String bytesToBase64(byte[] text); static String bytesToBase64Url(byte[] text); static Map<String, Object> queryParams(Object... params); static String numberToString(Object value, String mask); }### Answer:
@Test public void testQueryParams() throws Exception { System.out.println("queryParams"); Map<String, Object> expResult = new HashMap(); expResult.put("idempresa", 1L); expResult.put("idmoneda", 2L); Map<String, Object> result = Fn.queryParams("idempresa",1L,"idmoneda",2L); assertEquals(expResult, result); expResult = new HashMap(); expResult.put("idempresa", 1L); result = Fn.queryParams("idempresa",1L,"idmoneda"); assertEquals(expResult, result); } |
### Question:
IOUtil { public static boolean isFileExist(String filePath) { File f = new File(filePath); return f.exists() && !f.isDirectory(); } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testIsFileExist() { System.out.println("isFileExist"); String filePath = "./src/test/java/org/javabeanstack/util/prueba.xml"; boolean expResult = true; boolean result = IOUtil.isFileExist(filePath); assertEquals(expResult, result); } |
### Question:
IOUtil { public static boolean isFolderExist(String folder) { File f = new File(folder); return f.exists() && f.isDirectory(); } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testIsFolderExist() { System.out.println("isFolderExist"); String folder = "./src/test/java/org/javabeanstack/util/"; boolean expResult = true; boolean result = IOUtil.isFolderExist(folder); assertEquals(expResult, result); folder = "./src/test/java/org/javabeanstack/util"; result = IOUtil.isFolderExist(folder); assertEquals(expResult, result); folder = "./src/test/java/org/javabeanstack/noexiste/"; result = IOUtil.isFolderExist(folder); assertEquals(false, result); } |
### Question:
IOUtil { public static String addbs(String pathFolder) { if (Strings.isNullorEmpty(pathFolder)) { return pathFolder; } if (pathFolder.endsWith("/") || pathFolder.endsWith("\\")) { return pathFolder; } return pathFolder.trim() + File.separator; } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testAddbs() { System.out.println("addbs"); String pathFolder = "./src/test/java/org/javabeanstack/util"; String expResult = "./src/test/java/org/javabeanstack/util"+File.separator; String result = IOUtil.addbs(pathFolder); assertEquals(expResult, result); } |
### Question:
IOUtil { public static InputStream getResourceAsStream(Class clazz, String filePath){ return clazz.getResourceAsStream(filePath); } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testGetResourceAsStream() { System.out.println("getResourceAsStream"); Class clazz = IOUtil.class; String filePath = "/images/javabeanstack_commons.png"; InputStream result = IOUtil.getResourceAsStream(clazz, filePath); assertNotNull(result); filePath = "images/javabeanstack_commons.png"; result = IOUtil.getResourceAsStream(clazz, filePath); assertNull(result); } |
### Question:
IOUtil { public static Properties getPropertiesFrom(String filePath) { Properties properties = new Properties(); if (!isFileExist(filePath)) { return null; } try (InputStream input = new FileInputStream(filePath)) { properties.load(input); return properties; } catch (Exception ex) { Logger.getLogger(IOUtil.class).error(ex.getMessage()); } return null; } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testGetPropertiesFrom_String() { System.out.println("getPropertiesFrom_string"); String filePath = "./src/test/java/org/javabeanstack/io/ioutiltest.properties"; Properties result = IOUtil.getPropertiesFrom(filePath); assertNotNull(result); filePath = "./src/test/java/org/javabeanstack/io/noexiste.properties"; result = IOUtil.getPropertiesFrom(filePath); assertNull(result); }
@Test public void testGetPropertiesFrom_File() { System.out.println("getPropertiesFrom_file"); String folder = "./src/test/java/org/javabeanstack/io/"; File file = new File(folder+"ioutiltest.properties"); Properties result = IOUtil.getPropertiesFrom(file); assertNotNull(result); file = new File(folder+"noexiste.properties"); result = IOUtil.getPropertiesFrom(file); assertNull(result); } |
### Question:
IOUtil { public static Properties getPropertiesFromResource(Class clazz, String filePath) { Properties properties = new Properties(); try (InputStream input = getResourceAsStream(clazz, filePath)){ properties.load(input); return properties; } catch (Exception ex) { Logger.getLogger(IOUtil.class).error(ex.getMessage()); } return null; } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testGetPropertiesFromResource() { System.out.println("getPropertiesFromResource"); Class clazz = IOUtil.class; String filePath = "/test/ioutiltest.properties"; Properties result = IOUtil.getPropertiesFromResource(clazz, filePath); assertNotNull(result); filePath = "test/ioutiltest.properties"; result = IOUtil.getPropertiesFromResource(clazz, filePath); assertNull(result); } |
### Question:
IOUtil { public static String getPath(String file){ return FilenameUtils.getPath(file); } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testGetPath() { System.out.println("getPath"); String file = "c:/src/test/java/org/javabeanstack/util/prueba.xml"; String expResult = "src/test/java/org/javabeanstack/util/"; String result = IOUtil.getPath(file); assertEquals(expResult, result); } |
### Question:
IOUtil { public static String getFullPath(String file){ return FilenameUtils.getFullPath(file); } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testGetFullPath() { System.out.println("getFullPath"); String file = "c:/src/test/java/org/javabeanstack/util/prueba.xml"; String expResult = "c:/src/test/java/org/javabeanstack/util/"; String result = IOUtil.getFullPath(file); assertEquals(expResult, result); } |
### Question:
IOUtil { public static String getFullPathNoEndSeparator(String file){ return FilenameUtils.getFullPathNoEndSeparator(file); } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testGetFullPathNoEndSeparator() { System.out.println("getFullPathNoEndSeparator"); String file = "c:/src/test/java/org/javabeanstack/util/prueba.xml"; String expResult = "c:/src/test/java/org/javabeanstack/util"; String result = IOUtil.getFullPathNoEndSeparator(file); assertEquals(expResult, result); } |
### Question:
IOUtil { public static String getFileBaseName(String file){ return FilenameUtils.getBaseName(file); } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testGetFileBaseName() { System.out.println("getFileBaseName"); String file = "c:/src/test/java/org/javabeanstack/util/prueba.xml"; String expResult = "prueba"; String result = IOUtil.getFileBaseName(file); assertEquals(expResult, result); } |
### Question:
IOUtil { public static String getFileName(String file){ return FilenameUtils.getName(file); } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testGetFileName() { System.out.println("getFileName"); String file = "c:/src/test/java/org/javabeanstack/util/prueba.xml"; String expResult = "prueba.xml"; String result = IOUtil.getFileName(file); assertEquals(expResult, result); } |
### Question:
IOUtil { public static String getFileExtension(String file){ return FilenameUtils.getExtension(file); } private IOUtil(); static boolean isFileExist(String filePath); static boolean isFolderExist(String folder); static String addbs(String pathFolder); static InputStream getResourceAsStream(Class clazz, String filePath); static Properties getPropertiesFrom(String filePath); static Properties getPropertiesFrom(File file); static Properties getPropertiesFromResource(Class clazz, String filePath); static String getPath(String file); static String getFullPath(String file); static String getFullPathNoEndSeparator(String file); static String getFileBaseName(String file); static String getFileName(String file); static String getFileExtension(String file); static boolean writeBytesToFile(byte[] byteArray, String filePath); }### Answer:
@Test public void testGetFileExtension() { System.out.println("getFileExtension"); String file = "c:/src/test/java/org/javabeanstack/util/prueba.xml"; String expResult = "xml"; String result = IOUtil.getFileExtension(file); assertEquals(expResult, result); } |
### Question:
DataInfo { public static <T extends IDataRow> String getTableName(Class<T> classType) { try { Table entity = classType.getAnnotation(Table.class); return entity.name(); } catch (Exception ex) { ErrorManager.showError(ex, LOGGER); } return ""; } private DataInfo(); static boolean isPrimaryKey(Class<T> classType, String fieldname); static boolean isUniqueKey(Class<T> classType, String fieldname); static boolean isForeignKey(Class<T> classType, String fieldname); static boolean isFieldExist(Class<T> classType, String fieldname); static boolean isMethodExist(Class<T> classType, String methodName); static boolean isLazyFetch(Class<T> classType, String fieldname); static List<Field> getLazyMembers(Class<T> classType); static String getTableName(Class<T> classType); static String createQueryUkCommand(IDataRow ejb); static String getIdFieldName(Class<T> classType); static String[] getUniqueFields(Class<T> classType); static Object getIdvalue(IDataRow ejb); static boolean setIdvalue(IDataRow ejb, Object value); static Object getDefaultValue(T ejb, String fieldname); static void setDefaultValue(T ejb, String fieldname); static T getObjFk(T ejb, String objrelaName); static Field getDeclaredField(Class classType, String fieldname); static Field[] getDeclaredFields(Class classType); static Method getMethod(Class classType, String methodName); static Class getFieldType(Class classType, String fieldname); static Class getMethodReturnType(Class classType, String methodname); static Class getMethodReturnType(Class classType, String methodname, Boolean isGetter); static Object getFieldValue(Object ejb, String fieldname); static Boolean setFieldValue(Object ejb, String fieldname, Object value); }### Answer:
@Test public void test07GetTableName() { System.out.println("7-DataInfo - getTableName"); String expResult = "appuser"; String result = DataInfo.getTableName(AppUser.class); assertEquals(expResult, result); } |
### Question:
OAuthConsumer extends OAuthConsumerBase { @Override public Class<IAppAuthConsumer> getAuthConsumerClass() { try { return (Class<IAppAuthConsumer>) Class.forName("org.javabeanstack.model.appcatalog.AppAuthConsumer"); } catch (ClassNotFoundException ex) { System.out.println(ex.getMessage()); } return null; } @Override Class<IAppAuthConsumer> getAuthConsumerClass(); @Override Class<IAppAuthConsumerToken> getAuthConsumerTokenClass(); @Override IDBFilter getDBFilter(IAppAuthConsumerToken token); }### Answer:
@Test public void test00InstanceClass() throws InstantiationException, IllegalAccessException{ OAuthConsumerBase instance = new OAuthConsumerImpl(); IAppAuthConsumer consumer = instance.getAuthConsumerClass().newInstance(); assertNotNull(consumer); } |
### Question:
CipherUtil { public static String encryptBlowfishToHex(String clearText, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { return encryptToHex(CipherUtil.BLOWFISH, clearText, key); } private CipherUtil(); static String encryptBlowfishToHex(String clearText, String key); static String encryptBlowfishToBase64(String clearText, String key); static String decryptBlowfishFromHex(String encrypted, String key); static String decryptBlowfishFromBase64(String encrypted, String key); static byte[] encryptAES(String clearText, String key); static String encryptAES_ToHex(String clearText, String key); static String encryptAES_ToBase64(String clearText, String key); static String decryptAES(byte[] encrypted, String key); static String decryptAES_FromHex(String encryptedHex, String key); static SecretKey getSecureRandomKey(String algoritm, int keyBitSize); static SecretKey getSecureRandomKey(String algoritm); static final String BLOWFISH; static final String AES_CBC; }### Answer:
@Test public void testEncryptBlowfishToHex() throws Exception { System.out.println("encryptBlowfishToHex"); String clearText = "abcdefghijklmnñopqrstuvwxyzáéíóú"; String key = "123456á"; String expResult = clearText; String encrypted = CipherUtil.encryptBlowfishToHex(clearText, key); String decrypted = CipherUtil.decryptBlowfishFromHex(encrypted, key); assertEquals(expResult, decrypted); } |
### Question:
CipherUtil { public static String decryptBlowfishFromHex(String encrypted, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException { return decryptFromHex(CipherUtil.BLOWFISH, encrypted, key); } private CipherUtil(); static String encryptBlowfishToHex(String clearText, String key); static String encryptBlowfishToBase64(String clearText, String key); static String decryptBlowfishFromHex(String encrypted, String key); static String decryptBlowfishFromBase64(String encrypted, String key); static byte[] encryptAES(String clearText, String key); static String encryptAES_ToHex(String clearText, String key); static String encryptAES_ToBase64(String clearText, String key); static String decryptAES(byte[] encrypted, String key); static String decryptAES_FromHex(String encryptedHex, String key); static SecretKey getSecureRandomKey(String algoritm, int keyBitSize); static SecretKey getSecureRandomKey(String algoritm); static final String BLOWFISH; static final String AES_CBC; }### Answer:
@Test public void testDecryptBlowfishFromHex() throws Exception { System.out.println("decryptBlowfishFromHex"); String clearText = "abcdefghijklmnñopqrstuvwxyzáéíóú"; String key = "123456Á"; String expResult = clearText; String encrypted = CipherUtil.encryptBlowfishToHex(clearText, key); String decrypted = CipherUtil.decryptBlowfishFromHex(encrypted, key); assertEquals(expResult, decrypted); } |
### Question:
CipherUtil { public static String encryptBlowfishToBase64(String clearText, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { return encryptToBase64(CipherUtil.BLOWFISH, clearText, key); } private CipherUtil(); static String encryptBlowfishToHex(String clearText, String key); static String encryptBlowfishToBase64(String clearText, String key); static String decryptBlowfishFromHex(String encrypted, String key); static String decryptBlowfishFromBase64(String encrypted, String key); static byte[] encryptAES(String clearText, String key); static String encryptAES_ToHex(String clearText, String key); static String encryptAES_ToBase64(String clearText, String key); static String decryptAES(byte[] encrypted, String key); static String decryptAES_FromHex(String encryptedHex, String key); static SecretKey getSecureRandomKey(String algoritm, int keyBitSize); static SecretKey getSecureRandomKey(String algoritm); static final String BLOWFISH; static final String AES_CBC; }### Answer:
@Test public void testEncryptBlowfishToBase64() throws Exception { System.out.println("encryptBlowfishToBase64"); String clearText = "abcdefghijklmnñopqrstuvwxyzáéíóú"; String key = "123456á"; String expResult = clearText; String encrypted = CipherUtil.encryptBlowfishToBase64(clearText, key); System.out.println(encrypted); String decrypted = CipherUtil.decryptBlowfishFromBase64(encrypted, key); assertEquals(expResult, decrypted); } |
### Question:
CipherUtil { public static String decryptBlowfishFromBase64(String encrypted, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException { return decryptFromBase64(CipherUtil.BLOWFISH, encrypted, key); } private CipherUtil(); static String encryptBlowfishToHex(String clearText, String key); static String encryptBlowfishToBase64(String clearText, String key); static String decryptBlowfishFromHex(String encrypted, String key); static String decryptBlowfishFromBase64(String encrypted, String key); static byte[] encryptAES(String clearText, String key); static String encryptAES_ToHex(String clearText, String key); static String encryptAES_ToBase64(String clearText, String key); static String decryptAES(byte[] encrypted, String key); static String decryptAES_FromHex(String encryptedHex, String key); static SecretKey getSecureRandomKey(String algoritm, int keyBitSize); static SecretKey getSecureRandomKey(String algoritm); static final String BLOWFISH; static final String AES_CBC; }### Answer:
@Test public void testDecryptBlowfishFromBase64() throws Exception { System.out.println("decryptBlowfishFromBase64"); String clearText = "abcdefghijklmnñopqrstuvwxyzáéíóú"; String key = "123456á"; String expResult = clearText; String encrypted = CipherUtil.encryptBlowfishToBase64(clearText, key); String decrypted = CipherUtil.decryptBlowfishFromBase64(encrypted, key); assertEquals(expResult, decrypted); } |
### Question:
CipherUtil { public static byte[] encryptAES(String clearText, String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { return encrypt_AES_CBC(clearText, key); } private CipherUtil(); static String encryptBlowfishToHex(String clearText, String key); static String encryptBlowfishToBase64(String clearText, String key); static String decryptBlowfishFromHex(String encrypted, String key); static String decryptBlowfishFromBase64(String encrypted, String key); static byte[] encryptAES(String clearText, String key); static String encryptAES_ToHex(String clearText, String key); static String encryptAES_ToBase64(String clearText, String key); static String decryptAES(byte[] encrypted, String key); static String decryptAES_FromHex(String encryptedHex, String key); static SecretKey getSecureRandomKey(String algoritm, int keyBitSize); static SecretKey getSecureRandomKey(String algoritm); static final String BLOWFISH; static final String AES_CBC; }### Answer:
@Test public void testEncryptAES() throws Exception{ System.out.println("encryptAES"); String clearText = "abcdefghijklmnñopqrstuvwxyzáéíóú"; String key = "012345678901234567890123456789á"; String expResult = clearText; byte[] encrypted = CipherUtil.encryptAES(clearText, key); String decrypted = CipherUtil.decryptAES(encrypted, key); assertEquals(expResult, decrypted); String hex = Fn.bytesToHex(encrypted); Assert.assertArrayEquals(encrypted, Fn.hexToByte(hex)); } |
### Question:
CipherUtil { public static String decryptAES(byte[] encrypted, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { return new String(decrypt_AES_CBC(encrypted, key)); } private CipherUtil(); static String encryptBlowfishToHex(String clearText, String key); static String encryptBlowfishToBase64(String clearText, String key); static String decryptBlowfishFromHex(String encrypted, String key); static String decryptBlowfishFromBase64(String encrypted, String key); static byte[] encryptAES(String clearText, String key); static String encryptAES_ToHex(String clearText, String key); static String encryptAES_ToBase64(String clearText, String key); static String decryptAES(byte[] encrypted, String key); static String decryptAES_FromHex(String encryptedHex, String key); static SecretKey getSecureRandomKey(String algoritm, int keyBitSize); static SecretKey getSecureRandomKey(String algoritm); static final String BLOWFISH; static final String AES_CBC; }### Answer:
@Test public void testDecryptAES() throws Exception{ System.out.println("decryptAES"); byte[] text = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyzáéíóú".getBytes(); String clearText = new String(text); String key = "012345678901234567890123456789á"; String expResult = clearText; byte[] encrypted = CipherUtil.encryptAES(clearText, key); String hex = Fn.bytesToHex(encrypted); byte[] encrypted2 = Fn.hexToByte(hex); String decrypted = CipherUtil.decryptAES(encrypted2, key); assertEquals(expResult, decrypted); } |
### Question:
CipherUtil { public static String encryptAES_ToHex(String clearText, String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { return Fn.bytesToHex(encrypt_AES_CBC(clearText, key)); } private CipherUtil(); static String encryptBlowfishToHex(String clearText, String key); static String encryptBlowfishToBase64(String clearText, String key); static String decryptBlowfishFromHex(String encrypted, String key); static String decryptBlowfishFromBase64(String encrypted, String key); static byte[] encryptAES(String clearText, String key); static String encryptAES_ToHex(String clearText, String key); static String encryptAES_ToBase64(String clearText, String key); static String decryptAES(byte[] encrypted, String key); static String decryptAES_FromHex(String encryptedHex, String key); static SecretKey getSecureRandomKey(String algoritm, int keyBitSize); static SecretKey getSecureRandomKey(String algoritm); static final String BLOWFISH; static final String AES_CBC; }### Answer:
@Test public void testEncryptAES_ToHex() throws Exception { System.out.println("encryptAES_ToHex"); String clearText = "abcdefghijklmnñopqrstuvwxyzáéíóú"; String key = "012345678901234567890123456789"; String expResult = clearText; String encrypted = CipherUtil.encryptAES_ToHex(clearText, key); String decrypted = CipherUtil.decryptAES(Fn.hexToByte(encrypted), key); assertEquals(expResult, decrypted); } |
### Question:
CipherUtil { public static String encryptAES_ToBase64(String clearText, String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { return Fn.bytesToBase64(encrypt_AES_CBC(clearText, key)); } private CipherUtil(); static String encryptBlowfishToHex(String clearText, String key); static String encryptBlowfishToBase64(String clearText, String key); static String decryptBlowfishFromHex(String encrypted, String key); static String decryptBlowfishFromBase64(String encrypted, String key); static byte[] encryptAES(String clearText, String key); static String encryptAES_ToHex(String clearText, String key); static String encryptAES_ToBase64(String clearText, String key); static String decryptAES(byte[] encrypted, String key); static String decryptAES_FromHex(String encryptedHex, String key); static SecretKey getSecureRandomKey(String algoritm, int keyBitSize); static SecretKey getSecureRandomKey(String algoritm); static final String BLOWFISH; static final String AES_CBC; }### Answer:
@Test public void testEncryptAES_ToBase64() throws Exception { System.out.println("encryptAES_ToBase64"); String clearText = "abcdefghijklmnñopqrstuvwxyzáéíóú"; String key = "012345678901234567890123456789"; String expResult = clearText; String encrypted = CipherUtil.encryptAES_ToBase64(clearText, key); String decrypted = CipherUtil.decryptAES(Fn.base64ToBytes(encrypted), key); assertEquals(expResult, decrypted); } |
### Question:
CipherUtil { public static String decryptAES_FromHex(String encryptedHex, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { return new String(decrypt_AES_CBC(Fn.hexToByte(encryptedHex), key)); } private CipherUtil(); static String encryptBlowfishToHex(String clearText, String key); static String encryptBlowfishToBase64(String clearText, String key); static String decryptBlowfishFromHex(String encrypted, String key); static String decryptBlowfishFromBase64(String encrypted, String key); static byte[] encryptAES(String clearText, String key); static String encryptAES_ToHex(String clearText, String key); static String encryptAES_ToBase64(String clearText, String key); static String decryptAES(byte[] encrypted, String key); static String decryptAES_FromHex(String encryptedHex, String key); static SecretKey getSecureRandomKey(String algoritm, int keyBitSize); static SecretKey getSecureRandomKey(String algoritm); static final String BLOWFISH; static final String AES_CBC; }### Answer:
@Test public void testDecryptAES_FromHex() throws Exception { System.out.println("decryptAES_FromHex"); String clearText = "abcdefghijklmnñopqrstuvwxyzáéíóú"; String key = "012345678901234567890123456789"; String expResult = clearText; String encrypted = CipherUtil.encryptAES_ToHex(clearText, key); String decrypted = CipherUtil.decryptAES_FromHex(encrypted, key); assertEquals(expResult, decrypted); } |
### Question:
CipherUtil { public static SecretKey getSecureRandomKey(String algoritm, int keyBitSize) throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance(algoritm); SecureRandom secureRandom = new SecureRandom(); keyGenerator.init(keyBitSize, secureRandom); return keyGenerator.generateKey(); } private CipherUtil(); static String encryptBlowfishToHex(String clearText, String key); static String encryptBlowfishToBase64(String clearText, String key); static String decryptBlowfishFromHex(String encrypted, String key); static String decryptBlowfishFromBase64(String encrypted, String key); static byte[] encryptAES(String clearText, String key); static String encryptAES_ToHex(String clearText, String key); static String encryptAES_ToBase64(String clearText, String key); static String decryptAES(byte[] encrypted, String key); static String decryptAES_FromHex(String encryptedHex, String key); static SecretKey getSecureRandomKey(String algoritm, int keyBitSize); static SecretKey getSecureRandomKey(String algoritm); static final String BLOWFISH; static final String AES_CBC; }### Answer:
@Test public void testGetSecureRandomKey_String_int() throws Exception { System.out.println("getSecureRandomKey"); String algoritm = "AES"; int keyBitSize = 256; SecretKey result = CipherUtil.getSecureRandomKey(algoritm, keyBitSize); assertNotNull(result); }
@Test public void testGetSecureRandomKey_String() throws Exception { System.out.println("getSecureRandomKey"); String algoritm = "Blowfish"; SecretKey result = CipherUtil.getSecureRandomKey(algoritm); assertNotNull(result); } |
### Question:
AbstractAnalyzedOp extends AnalyzedOp { @Override public AnalyzedOpType getType() { return type; } AbstractAnalyzedOp(KvValue<?> mongoDocId, AnalyzedOpType type,
@Nullable Function<KvDocument, KvDocument> calculateFun); @Override abstract String toString(); @Override AnalyzedOpType getType(); @Override KvValue<?> getMongoDocId(); @Override Status<?> getMismatchErrorMessage(); @Override KvDocument calculateDocToInsert(Function<AnalyzedOp, KvDocument> fetchedDocFun); }### Answer:
@Test public void requiresToFetchToroIdTest() { AnalyzedOp op = getAnalyzedOp(defaultMongoDocId); assertEquals("", op.getType().requiresToFetchToroId(), op.requiresToFetchToroId()); }
@Test public void requiresMatchTest() { AnalyzedOp op = getAnalyzedOp(defaultMongoDocId); assertEquals("", op.getType().requiresMatch(), op.requiresMatch()); }
@Test public void requiresFetchTest() { AnalyzedOp op = getAnalyzedOp(defaultMongoDocId); assertEquals("", op.getType().requiresFetch(), op.requiresFetch()); }
@Test public void deletesTest() { AnalyzedOp op = getAnalyzedOp(defaultMongoDocId); assertEquals("", op.getType().deletes(), op.deletes()); } |
### Question:
AbstractMongoOplogReader implements OplogReader { @Override public MongoCursor<OplogOperation> queryGte(OpTime lastFetchedOpTime) throws MongoException { BsonDocument query = DefaultBsonValues.newDocument( "ts", DefaultBsonValues.newDocument("$gte", lastFetchedOpTime.getTimestamp()) ); EnumSet<QueryOption> flags = EnumSet.of( QueryOption.AWAIT_DATA, QueryOption.TAILABLE_CURSOR ); return query(query, flags, NATURAL_ORDER_SORT); } @Override MongoCursor<OplogOperation> queryGte(OpTime lastFetchedOpTime); @Override OplogOperation getLastOp(); @Override OplogOperation getFirstOp(); @Override MongoCursor<OplogOperation> between(
OpTime from, boolean includeFrom,
OpTime to, boolean includeTo); MongoCursor<OplogOperation> query(BsonDocument query, EnumSet<QueryOption> flags,
BsonDocument sortBy); }### Answer:
@Test public void testQueryGTE() throws Exception { } |
### Question:
AbstractMongoOplogReader implements OplogReader { @Override public OplogOperation getLastOp() throws OplogStartMissingException, OplogOperationUnsupported, MongoException { return getFirstOrLastOp(false); } @Override MongoCursor<OplogOperation> queryGte(OpTime lastFetchedOpTime); @Override OplogOperation getLastOp(); @Override OplogOperation getFirstOp(); @Override MongoCursor<OplogOperation> between(
OpTime from, boolean includeFrom,
OpTime to, boolean includeTo); MongoCursor<OplogOperation> query(BsonDocument query, EnumSet<QueryOption> flags,
BsonDocument sortBy); }### Answer:
@Test public void testGetLastOp() throws Exception { } |
### Question:
AbstractMongoOplogReader implements OplogReader { @Override public OplogOperation getFirstOp() throws OplogStartMissingException, OplogOperationUnsupported, MongoException { return getFirstOrLastOp(true); } @Override MongoCursor<OplogOperation> queryGte(OpTime lastFetchedOpTime); @Override OplogOperation getLastOp(); @Override OplogOperation getFirstOp(); @Override MongoCursor<OplogOperation> between(
OpTime from, boolean includeFrom,
OpTime to, boolean includeTo); MongoCursor<OplogOperation> query(BsonDocument query, EnumSet<QueryOption> flags,
BsonDocument sortBy); }### Answer:
@Test public void testGetFirstOp() throws Exception { } |
### Question:
AbstractMongoOplogReader implements OplogReader { @Override public MongoCursor<OplogOperation> between( OpTime from, boolean includeFrom, OpTime to, boolean includeTo) throws MongoException { BsonArrayBuilder conditions = new BsonArrayBuilder(); conditions.add( DefaultBsonValues.newDocument( "ts", DefaultBsonValues.newDocument(includeFrom ? "$gte" : "$gt", from.getTimestamp()) ) ); conditions.add( DefaultBsonValues.newDocument( "ts", DefaultBsonValues.newDocument(includeTo ? "$lte" : "$lt", to.getTimestamp()) ) ); EnumSet<QueryOption> flags = EnumSet.noneOf(QueryOption.class); return query( DefaultBsonValues.newDocument("$and", conditions.build()), flags, NATURAL_ORDER_SORT); } @Override MongoCursor<OplogOperation> queryGte(OpTime lastFetchedOpTime); @Override OplogOperation getLastOp(); @Override OplogOperation getFirstOp(); @Override MongoCursor<OplogOperation> between(
OpTime from, boolean includeFrom,
OpTime to, boolean includeTo); MongoCursor<OplogOperation> query(BsonDocument query, EnumSet<QueryOption> flags,
BsonDocument sortBy); }### Answer:
@Test public void testBetween() throws Exception { } |
### Question:
AbstractMongoOplogReader implements OplogReader { public MongoCursor<OplogOperation> query(BsonDocument query, EnumSet<QueryOption> flags, BsonDocument sortBy) throws MongoException { Preconditions.checkState(!isClosed(), "You have to connect this client before"); MongoConnection connection = consumeConnection(); MongoCursor<BsonDocument> cursor = connection.query( DATABASE, COLLECTION, query, 0, 0, new QueryOptions(flags), sortBy, null ); return new MyCursor<>( connection, TransformationMongoCursor.create( cursor, OplogOperationParser.asFunction() ) ); } @Override MongoCursor<OplogOperation> queryGte(OpTime lastFetchedOpTime); @Override OplogOperation getLastOp(); @Override OplogOperation getFirstOp(); @Override MongoCursor<OplogOperation> between(
OpTime from, boolean includeFrom,
OpTime to, boolean includeTo); MongoCursor<OplogOperation> query(BsonDocument query, EnumSet<QueryOption> flags,
BsonDocument sortBy); }### Answer:
@Test public void testQuery() throws Exception { } |
### Question:
SimpleRegExpDecoder { public static Pattern decode(String simpleRegExp) { StringBuilder resultPatternBuilder = new StringBuilder(); boolean quoted = false; final int length = simpleRegExp.length(); for (int index = 0; index < length; index++) { char simpleRegExpChar = simpleRegExp.charAt(index); if (simpleRegExpChar == ANY_CHARACTER) { if (quoted) { resultPatternBuilder.append("\\E"); quoted = false; } resultPatternBuilder.append(".*"); } else { if (!quoted) { resultPatternBuilder.append("\\Q"); quoted = true; } if (simpleRegExpChar == DELIMITER) { index++; simpleRegExpChar = simpleRegExp.charAt(index); } resultPatternBuilder.append(simpleRegExpChar); } } if (quoted) { resultPatternBuilder.append("\\E"); } return Pattern.compile(resultPatternBuilder.toString()); } static Pattern decode(String simpleRegExp); }### Answer:
@Test public void decodeTest() { Assert .assertEquals("\\Qmine_and_your\\E", SimpleRegExpDecoder.decode("mine_and_your").pattern()); Assert.assertEquals("\\Qmine_\\E.*\\Q_your\\E", SimpleRegExpDecoder.decode("mine_*_your") .pattern()); Assert.assertEquals("\\Qmine_*_your\\E", SimpleRegExpDecoder.decode("mine_\\*_your").pattern()); Assert.assertEquals("\\Qmine_\\\\E.*\\Q_your\\E", SimpleRegExpDecoder.decode( "min\\e_\\\\*_yo\\ur").pattern()); Assert.assertEquals(".*\\Q_and_your\\E", SimpleRegExpDecoder.decode("*_and_your").pattern()); Assert.assertEquals("\\Qmine_and_\\E.*", SimpleRegExpDecoder.decode("mine_and_*").pattern()); Assert.assertEquals("\\Q*_and_your\\E", SimpleRegExpDecoder.decode("\\*_and_your").pattern()); Assert.assertEquals("\\Qmine_and_*\\E", SimpleRegExpDecoder.decode("mine_and_\\*").pattern()); } |
### Question:
BatchMetaCollection implements MutableMetaCollection { public final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts() { return docPartsByRef.values().stream(); } BatchMetaCollection(MutableMetaCollection delegate); @Override ImmutableMetaCollection getOrigin(); final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts(); @DoNotChange Iterable<BatchMetaDocPart> getOnBatchModifiedMetaDocParts(); @Override BatchMetaDocPart getMetaDocPartByTableRef(TableRef tableRef); @Override BatchMetaDocPart getMetaDocPartByIdentifier(String docPartId); @Override BatchMetaDocPart addMetaDocPart(TableRef tableRef, String identifier); @Override Stream<? extends MutableMetaDocPart> streamModifiedMetaDocParts(); @Override MutableMetaIndex getMetaIndexByName(String indexName); @Override Stream<? extends MutableMetaIndex> streamContainedMetaIndexes(); @Override MutableMetaIndex addMetaIndex(String name, boolean unique); @Override boolean removeMetaIndexByName(String indexName); @Override Stream<ChangedElement<MutableMetaIndex>> streamModifiedMetaIndexes(); @Override Optional<ChangedElement<MutableMetaIndex>> getModifiedMetaIndexByName(String idxName); @Override List<Tuple2<MetaIndex, List<String>>> getMissingIndexesForNewField(
MutableMetaDocPart docPart,
MetaField newField); @Override Optional<ImmutableMetaDocPart> getAnyDocPartWithMissedDocPartIndex(
ImmutableMetaCollection oldStructure,
MutableMetaIndex changed); @Override Optional<? extends MetaIdentifiedDocPartIndex> getAnyOrphanDocPartIndex(
ImmutableMetaCollection oldStructure,
MutableMetaIndex changed); @Override ImmutableMetaCollection immutableCopy(); @Override String getName(); @Override String getIdentifier(); @Override String toString(); }### Answer:
@Test public void testConstructor() { assertTrue("The constructor do not copy doc parts contained by the delegate", collection.streamContainedMetaDocParts() .findAny() .isPresent() ); assertTrue("There is at least one doc part that is marked as created on the current branch", collection.streamContainedMetaDocParts() .noneMatch((docPart) -> docPart.isCreatedOnCurrentBatch()) ); } |
### Question:
BatchMetaCollection implements MutableMetaCollection { @Override public String getName() { return delegate.getName(); } BatchMetaCollection(MutableMetaCollection delegate); @Override ImmutableMetaCollection getOrigin(); final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts(); @DoNotChange Iterable<BatchMetaDocPart> getOnBatchModifiedMetaDocParts(); @Override BatchMetaDocPart getMetaDocPartByTableRef(TableRef tableRef); @Override BatchMetaDocPart getMetaDocPartByIdentifier(String docPartId); @Override BatchMetaDocPart addMetaDocPart(TableRef tableRef, String identifier); @Override Stream<? extends MutableMetaDocPart> streamModifiedMetaDocParts(); @Override MutableMetaIndex getMetaIndexByName(String indexName); @Override Stream<? extends MutableMetaIndex> streamContainedMetaIndexes(); @Override MutableMetaIndex addMetaIndex(String name, boolean unique); @Override boolean removeMetaIndexByName(String indexName); @Override Stream<ChangedElement<MutableMetaIndex>> streamModifiedMetaIndexes(); @Override Optional<ChangedElement<MutableMetaIndex>> getModifiedMetaIndexByName(String idxName); @Override List<Tuple2<MetaIndex, List<String>>> getMissingIndexesForNewField(
MutableMetaDocPart docPart,
MetaField newField); @Override Optional<ImmutableMetaDocPart> getAnyDocPartWithMissedDocPartIndex(
ImmutableMetaCollection oldStructure,
MutableMetaIndex changed); @Override Optional<? extends MetaIdentifiedDocPartIndex> getAnyOrphanDocPartIndex(
ImmutableMetaCollection oldStructure,
MutableMetaIndex changed); @Override ImmutableMetaCollection immutableCopy(); @Override String getName(); @Override String getIdentifier(); @Override String toString(); }### Answer:
@Test public void testGetName() { assertEquals(collection.getName(), delegate.getName()); } |
### Question:
BatchMetaCollection implements MutableMetaCollection { @Override public String getIdentifier() { return delegate.getIdentifier(); } BatchMetaCollection(MutableMetaCollection delegate); @Override ImmutableMetaCollection getOrigin(); final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts(); @DoNotChange Iterable<BatchMetaDocPart> getOnBatchModifiedMetaDocParts(); @Override BatchMetaDocPart getMetaDocPartByTableRef(TableRef tableRef); @Override BatchMetaDocPart getMetaDocPartByIdentifier(String docPartId); @Override BatchMetaDocPart addMetaDocPart(TableRef tableRef, String identifier); @Override Stream<? extends MutableMetaDocPart> streamModifiedMetaDocParts(); @Override MutableMetaIndex getMetaIndexByName(String indexName); @Override Stream<? extends MutableMetaIndex> streamContainedMetaIndexes(); @Override MutableMetaIndex addMetaIndex(String name, boolean unique); @Override boolean removeMetaIndexByName(String indexName); @Override Stream<ChangedElement<MutableMetaIndex>> streamModifiedMetaIndexes(); @Override Optional<ChangedElement<MutableMetaIndex>> getModifiedMetaIndexByName(String idxName); @Override List<Tuple2<MetaIndex, List<String>>> getMissingIndexesForNewField(
MutableMetaDocPart docPart,
MetaField newField); @Override Optional<ImmutableMetaDocPart> getAnyDocPartWithMissedDocPartIndex(
ImmutableMetaCollection oldStructure,
MutableMetaIndex changed); @Override Optional<? extends MetaIdentifiedDocPartIndex> getAnyOrphanDocPartIndex(
ImmutableMetaCollection oldStructure,
MutableMetaIndex changed); @Override ImmutableMetaCollection immutableCopy(); @Override String getName(); @Override String getIdentifier(); @Override String toString(); }### Answer:
@Test public void testGetIdentifier() { assertEquals(collection.getIdentifier(), delegate.getIdentifier()); } |
### Question:
CompletionExceptions { public static Throwable getFirstNonCompletionException(Throwable ex) { Throwable throwableResult = ex; while (isCompletionException(throwableResult)) { Throwable cause = throwableResult.getCause(); if (cause == null || cause == throwableResult) { return throwableResult; } throwableResult = cause; } assert throwableResult != null; assert !(throwableResult instanceof CompletionException) || throwableResult.getCause() == null; return throwableResult; } private CompletionExceptions(); static Throwable getFirstNonCompletionException(Throwable ex); }### Answer:
@Test public void firstNonCompletionExceptionIsReturned() throws Exception { Throwable nullPointerException = new NullPointerException(); Throwable completionException = new CompletionException("message", nullPointerException); Throwable result = CompletionExceptions.getFirstNonCompletionException(completionException); assertEquals(nullPointerException, result); }
@Test public void ifHasNoNestedExceptionCompletionExceptionIsReturned() throws Exception { Throwable completionException = new CompletionException("message", null); Throwable result = CompletionExceptions.getFirstNonCompletionException(completionException); assertEquals(completionException, result); } |
### Question:
HexUtils { public static String bytes2Hex(@Nonnull byte[] bytes) { checkNotNull(bytes, "bytes"); final int length = bytes.length; final char[] chars = new char[length << 1]; int index; int charPos = 0; for (int i = 0; i < length; i++) { index = (bytes[i] & 0xFF) << 1; chars[charPos++] = BYTE_HEX_VALUES[index++]; chars[charPos++] = BYTE_HEX_VALUES[index]; } return new String(chars); } static String bytes2Hex(@Nonnull byte[] bytes); static String bytes2Hex(@Nonnull Collection<Byte> bytes); static void bytes2Hex(@Nonnull byte[] bytes, StringBuilder output); static byte[] hex2Bytes(@Nonnull String value); }### Answer:
@Test public void bytes2HexArray() { String expected = DatatypeConverter.printHexBinary(bytes); String result = HexUtils.bytes2Hex(bytes); assertEquals(expected, result); }
@Test public void bytes2HexCollection() { String expected = DatatypeConverter.printHexBinary(bytes); List<Byte> collectionBytes = new ArrayList<>(bytes.length); for (byte b : bytes) { collectionBytes.add(b); } String result = HexUtils.bytes2Hex(collectionBytes); assertEquals(expected, result); } |
### Question:
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public ToroMetricRegistry createSubRegistry(String key, String value) { return new DirectoryToroMetricRegistry( directory.createDirectory(key, value), safeMetricRegistry ); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testCreateSubRegistry_2_illegalKey() { registry.createSubRegistry("a-illegal-key", "avalue"); }
@Test(expected = IllegalArgumentException.class) public void testCreateSubRegistry_2_illegalValue() { registry.createSubRegistry("aValue", "a-illegal-value"); }
@Test(expected = IllegalArgumentException.class) public void testCreateSubRegistry_default_illegalValue() { registry.createSubRegistry("a-illegal-value"); } |
### Question:
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Counter counter(String finalName) { return safeMetricRegistry.counter(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }### Answer:
@Test public void testCounter() { String sName = "legalName"; Name name = directory.createName(sName); Counter metric = registry.counter(sName); verify(safeRegistry).counter(name); assertThat(metric, is(safeRegistry.counter(name))); }
@Test(expected = IllegalArgumentException.class) public void testIllegalCounter() { String sName = "illegal-Name"; registry.counter(sName); } |
### Question:
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Meter meter(String finalName) { return safeMetricRegistry.meter(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }### Answer:
@Test public void testMeter() { String sName = "legalName"; Name name = directory.createName(sName); Meter metric = registry.meter(sName); verify(safeRegistry).meter(name); assertThat(metric, is(safeRegistry.meter(name))); }
@Test(expected = IllegalArgumentException.class) public void testIllegalMeter() { String sName = "illegal-Name"; registry.meter(sName); } |
### Question:
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Histogram histogram(String finalName, boolean resetOnSnapshot) { return safeMetricRegistry.histogram(directory.createName(finalName), resetOnSnapshot); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }### Answer:
@Test public void testHistogram() { String sName = "legalName"; Name name = directory.createName(sName); Histogram metric = registry.histogram(sName); verify(safeRegistry).histogram(name, false); assertThat(metric, is(safeRegistry.histogram(name))); }
@Test(expected = IllegalArgumentException.class) public void testIllegalHistogram() { String sName = "illegal-Name"; registry.histogram(sName); } |
### Question:
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Timer timer(String finalName, boolean resetOnSnapshot) { return safeMetricRegistry.timer(directory.createName(finalName), resetOnSnapshot); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }### Answer:
@Test public void testTimer() { String sName = "legalName"; Name name = directory.createName(sName); Timer metric = registry.timer(sName); verify(safeRegistry).timer(name, false); assertThat(metric, is(safeRegistry.timer(name))); }
@Test(expected = IllegalArgumentException.class) public void testIllegalTimer() { String sName = "illegal-Name"; registry.timer(sName); } |
### Question:
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public <T> SettableGauge<T> gauge(String finalName) { return safeMetricRegistry.gauge(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }### Answer:
@Test public void testGauge() { String sName = "legalName"; Name name = directory.createName(sName); SettableGauge<?> metric = registry.gauge(sName); verify(safeRegistry).gauge(name); assertThat(metric, is(safeRegistry.gauge(name))); }
@Test(expected = IllegalArgumentException.class) public void testIllegalGauge() { String sName = "illegal-Name"; registry.gauge(sName); } |
### Question:
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public <T extends Metric> T register(String finalName, T metric) { return safeMetricRegistry.register(directory.createName(finalName), metric); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }### Answer:
@Test public void testRegister() { String sName = "legalName"; Name name = directory.createName(sName); Counter actualCounter = new Counter(); Counter metric = registry.register(sName, actualCounter); verify(safeRegistry).register(name, actualCounter); assertThat(metric, is(safeRegistry.register(name, actualCounter))); assertThat(metric, is(safeRegistry.counter(name))); }
@Test(expected = IllegalArgumentException.class) public void testIllegalRegister() { String sName = "illegal-Name"; registry.register(sName, new Counter()); } |
### Question:
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public boolean remove(String finalName) { return safeMetricRegistry.remove(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }### Answer:
@Test public void testRemove() { String sName = "legalName"; Name name = directory.createName(sName); registry.remove(sName); verify(safeRegistry).remove(name); }
@Test(expected = IllegalArgumentException.class) public void testIllegalRemove() { String sName = "illegal-Name"; registry.remove(sName); } |
### Question:
EssentialInjectorFactory { public static Injector createEssentialInjector(LoggerFactory lifecycleLoggerFactory) { return createEssentialInjector(lifecycleLoggerFactory, () -> true, Clock.systemUTC()); } private EssentialInjectorFactory(); static Injector createEssentialInjector(LoggerFactory lifecycleLoggerFactory); static Injector createEssentialInjector(LoggerFactory lifecycleLoggerFactory,
MetricsConfig metricsConfig, Clock clock); static Injector createEssentialInjector(
LoggerFactory lifecycleLoggerFactory,
MetricsConfig metricsConfig,
Clock clock,
Stage stage); }### Answer:
@Test public void testCreateEssentialInjector() { EssentialInjectorFactory.createEssentialInjector(DefaultLoggerFactory.getInstance()); } |
### Question:
AbstractAnalyzedOp extends AnalyzedOp { @Override public Status<?> getMismatchErrorMessage() throws UnsupportedOperationException { if (!requiresMatch()) { throw new UnsupportedOperationException(); } return Status.from(ErrorCode.OPERATION_FAILED); } AbstractAnalyzedOp(KvValue<?> mongoDocId, AnalyzedOpType type,
@Nullable Function<KvDocument, KvDocument> calculateFun); @Override abstract String toString(); @Override AnalyzedOpType getType(); @Override KvValue<?> getMongoDocId(); @Override Status<?> getMismatchErrorMessage(); @Override KvDocument calculateDocToInsert(Function<AnalyzedOp, KvDocument> fetchedDocFun); }### Answer:
@Test public void getMismatchErrorMessageTest() { AnalyzedOp op = getAnalyzedOp(defaultMongoDocId); if (op.getType().requiresMatch()) { Status<?> status = op.getMismatchErrorMessage(); assertNotNull( "The mismatch error of an analyzed operation that requires match must not be null", status); assertFalse("The mismatch error of an analyzed operation that requires match must not be OK", status.isOk()); } else { try { op.getMismatchErrorMessage(); fail("An analyzed operation that does not require match must throw a " + UnsupportedOperationException.class + " when its mismatch error is " + "requested"); } catch (UnsupportedOperationException ex) { } } } |
### Question:
AbstractAnalyzedOp extends AnalyzedOp { @Override public KvValue<?> getMongoDocId() { return mongoDocId; } AbstractAnalyzedOp(KvValue<?> mongoDocId, AnalyzedOpType type,
@Nullable Function<KvDocument, KvDocument> calculateFun); @Override abstract String toString(); @Override AnalyzedOpType getType(); @Override KvValue<?> getMongoDocId(); @Override Status<?> getMismatchErrorMessage(); @Override KvDocument calculateDocToInsert(Function<AnalyzedOp, KvDocument> fetchedDocFun); }### Answer:
@Test public void getMongoDocIdTest() { assertEquals("Unexpected mongo doc id.", defaultMongoDocId, getAnalyzedOp(defaultMongoDocId) .getMongoDocId()); } |
### Question:
FastMath { public static Vector2 rotateVector90(Vector2 v, Vector2 newVector) { float x = -v.y; float y = v.x; newVector.set(x, y); return newVector; } static Vector2 rotateVector90(Vector2 v, Vector2 newVector); static Vector2 rotateVector90(Vector2 v); static boolean checkVectorsParallel(Vector2 v1, Vector2 v2); static boolean checkIfLinesAreEquals(Line a, Line b); }### Answer:
@Test public void testRotateVector90() { Vector2 v1 = new Vector2(1, 0); Vector2 expected = new Vector2(0, 1); Vector2 rotatedVector = FastMath.rotateVector90(v1); assertEquals( "wrong rotated vector calculation, expected: " + expected + ", calculated vector: " + rotatedVector, true, (expected.x == rotatedVector.x && expected.y == rotatedVector.y)); } |
### Question:
FastMath { public static boolean checkVectorsParallel(Vector2 v1, Vector2 v2) { Vector2 rotatedVector1 = rotateVector90(v1, Vector2Pool.create()); float dotProduct = rotatedVector1.dot(v2); Vector2Pool.free(rotatedVector1); return dotProduct == 0; } static Vector2 rotateVector90(Vector2 v, Vector2 newVector); static Vector2 rotateVector90(Vector2 v); static boolean checkVectorsParallel(Vector2 v1, Vector2 v2); static boolean checkIfLinesAreEquals(Line a, Line b); }### Answer:
@Test public void testCheckVectorsParallel() { Vector2 v1 = new Vector2(1, 1); Vector2 v2 = new Vector2(1, 1); assertEquals(true, FastMath.checkVectorsParallel(v1, v2)); assertEquals(true, FastMath.checkVectorsParallel(v2, v1)); Vector2 v3 = new Vector2(1, 2); assertEquals(false, FastMath.checkVectorsParallel(v1, v3)); assertEquals(false, FastMath.checkVectorsParallel(v3, v1)); Vector2 v4 = new Vector2(2, 2); assertEquals(true, FastMath.checkVectorsParallel(v1, v4)); assertEquals(true, FastMath.checkVectorsParallel(v4, v1)); } |
### Question:
FastMath { public static boolean checkIfLinesAreEquals(Line a, Line b) { if (!checkVectorsParallel(a.getDirection(), b.getDirection())) { return false; } Vector2 d = Vector2Pool.create(); d.set(a.getBase().x, a.getBase().y); d.sub(b.getBase()); Vector2Pool.free(d); return checkVectorsParallel(d, a.getDirection()); } static Vector2 rotateVector90(Vector2 v, Vector2 newVector); static Vector2 rotateVector90(Vector2 v); static boolean checkVectorsParallel(Vector2 v1, Vector2 v2); static boolean checkIfLinesAreEquals(Line a, Line b); }### Answer:
@Test public void testCheckIfLinesAreEquals() { Line line1 = new Line(0, 0, 1, 1); Line line2 = new Line(0, 0, 1, 1); assertEquals(true, FastMath.checkIfLinesAreEquals(line1, line2)); assertEquals(true, FastMath.checkIfLinesAreEquals(line2, line1)); Line line3 = new Line(1, 1, 1, 1); assertEquals(true, FastMath.checkIfLinesAreEquals(line1, line3)); assertEquals(true, FastMath.checkIfLinesAreEquals(line3, line1)); Line line4 = new Line(0, 0, -1, 1); assertEquals(false, FastMath.checkIfLinesAreEquals(line1, line4)); assertEquals(false, FastMath.checkIfLinesAreEquals(line4, line1)); Line line5 = new Line(0, 0, 2, 2); assertEquals(true, FastMath.checkIfLinesAreEquals(line1, line5)); assertEquals(true, FastMath.checkIfLinesAreEquals(line5, line1)); } |
### Question:
CCircle extends CShape { @Override public boolean overlaps(CShape obj) { if (obj instanceof CCircle) { CCircle circle = (CCircle) obj; float dx = getCenterX() - circle.getCenterX(); float dy = getCenterY() - circle.getCenterY(); float distance = dx * dx + dy * dy; float radiusSum = radius + circle.radius; return distance <= radiusSum * radiusSum; } else if (obj instanceof CPoint) { return ColliderUtils.testCirclePointCollision(this, (CPoint) obj); } else { throw new IllegalArgumentException("shape class " + obj.getClass() + " isnt supported."); } } CCircle(float x, float y, float radius); @Override float getCenterX(); @Override float getCenterY(); float getRadius(); @Override boolean overlaps(CShape obj); @Override void drawShape(GameTime time, CameraWrapper camera, ShapeRenderer shapeRenderer, Color color); }### Answer:
@Test public void testOverlapsCircle() { CCircle circle1 = new CCircle(0, 0, 50); CCircle circle2 = new CCircle(200, 200, 50); assertEquals(false, circle1.overlaps(circle2)); CCircle circle3 = new CCircle(100, 100, 50); assertEquals(false, circle1.overlaps(circle3)); CCircle circle4 = new CCircle(100, 0, 50); assertEquals(true, circle1.overlaps(circle4)); CCircle circle5 = new CCircle(100, 0, 55); assertEquals(true, circle1.overlaps(circle4)); } |
### Question:
CRectangle extends CShape { @Override public boolean overlaps(CShape obj) { if (obj instanceof CRectangle) { CRectangle rect = (CRectangle) obj; return x <= rect.getX() + rect.width && getX() + width >= rect.getX() && getY() <= rect.getY() + rect.height && getY() + height >= rect.getY(); } else { throw new IllegalArgumentException("shape class " + obj.getClass() + " isnt supported."); } } CRectangle(float x, float y, float width, float height); float getX(); float getY(); float getWidth(); float getHeight(); @Override float getCenterX(); @Override float getCenterY(); @Override boolean overlaps(CShape obj); @Override void drawShape(GameTime time, CameraWrapper camera, ShapeRenderer shapeRenderer, Color color); }### Answer:
@Test public void testOverlapsRectangle() { CRectangle rect1 = new CRectangle(0, 0, 100, 100); CRectangle rect2 = new CRectangle(0, 0, 100, 100); assertEquals(true, rect1.overlaps(rect2)); CRectangle rect3 = new CRectangle(-10, -10, 5, 5); assertEquals(false, rect1.overlaps(rect3)); CRectangle rect4 = new CRectangle(100, 100, 100, 100); assertEquals(true, rect1.overlaps(rect4)); CRectangle rect5 = new CRectangle(50, 50, 100, 100); assertEquals(true, rect1.overlaps(rect5)); } |
### Question:
ColliderUtils { public static boolean overlaping(float minA, float maxA, float minB, float maxB) { if (maxA < minA) { float a = maxA; maxA = minA; minA = a; } if (maxB < minB) { float b = minB; maxB = minB; minB = b; } return minB <= maxA && minA <= maxB; } static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2); static boolean testCircleCircleCollision(Circle circle1, Circle circle2); static boolean testCirclePointCollision(CCircle circle, CPoint point); static boolean testLineCollision(Line a, Line b); static boolean onOneSide(Line axis, Segment s); static boolean testSegmentCollision(Segment a, Segment b); static boolean overlaping(float minA, float maxA, float minB, float maxB); }### Answer:
@Test public void testOverlaping() { assertEquals("values arent overlaping, but method returns true.", false, ColliderUtils.overlaping(0, 1, 2, 3)); assertEquals("values arent overlaping, but method returns true.", false, ColliderUtils.overlaping(2, 3, 3.1f, 4)); assertEquals("values are overlaping, but method returns false.", true, ColliderUtils.overlaping(0, 3, 2, 3)); assertEquals("values are overlaping, but method returns false.", true, ColliderUtils.overlaping(3, 4, 2, 3)); assertEquals("values are overlaping, but method returns false.", true, ColliderUtils.overlaping(4, 3, 2, 3)); } |
### Question:
ColliderUtils { public static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2) { return rect1.overlaps(rect2); } static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2); static boolean testCircleCircleCollision(Circle circle1, Circle circle2); static boolean testCirclePointCollision(CCircle circle, CPoint point); static boolean testLineCollision(Line a, Line b); static boolean onOneSide(Line axis, Segment s); static boolean testSegmentCollision(Segment a, Segment b); static boolean overlaping(float minA, float maxA, float minB, float maxB); }### Answer:
@Test public void testRectangleRectangleCollisionTest() { Rectangle rect1 = new Rectangle(0, 0, 100, 100); Rectangle rect2 = new Rectangle(99, 99, 100, 100); assertEquals("rectangle is overlaping, but collision test returns false.", true, ColliderUtils.testRectangleRectangleCollision(rect1, rect2)); } |
### Question:
ColliderUtils { public static boolean testCirclePointCollision(CCircle circle, CPoint point) { float dx = circle.getCenterX() - point.getCenterX(); float dy = circle.getCenterY() - point.getCenterY(); float distance = dx * dx + dy * dy; float radiusSum = circle.getRadius(); return distance <= radiusSum * radiusSum; } static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2); static boolean testCircleCircleCollision(Circle circle1, Circle circle2); static boolean testCirclePointCollision(CCircle circle, CPoint point); static boolean testLineCollision(Line a, Line b); static boolean onOneSide(Line axis, Segment s); static boolean testSegmentCollision(Segment a, Segment b); static boolean overlaping(float minA, float maxA, float minB, float maxB); }### Answer:
@Test public void testOverlapingCirclePoint() { CCircle circle = new CCircle(0, 0, 5); CPoint point1 = new CPoint(0, 0); assertEquals(true, ColliderUtils.testCirclePointCollision(circle, point1)); CPoint point2 = new CPoint(5, 0); assertEquals(true, ColliderUtils.testCirclePointCollision(circle, point2)); CPoint point3 = new CPoint(10, 10); assertEquals(false, ColliderUtils.testCirclePointCollision(circle, point3)); CPoint point4 = new CPoint(0, -5); assertEquals(true, ColliderUtils.testCirclePointCollision(circle, point4)); } |
### Question:
DemoController { @RequestMapping("/now") public String now(){ return "hello"; } @RequestMapping("/now") String now(); }### Answer:
@Test public void now() throws Exception { ResultActions resultActions = this.mvc.perform(new RequestBuilder() { @Override public MockHttpServletRequest buildRequest(ServletContext servletContext) { return new MockHttpServletRequest(RequestMethod.GET.name(), "/now"); } }).andExpect(status().isOk()).andExpect(content().string("hello")); String contentAsString = resultActions.andReturn().getResponse().getContentAsString(); assertEquals(contentAsString, "hello"); } |
### Question:
Mockito { public static <T> When<T> when(T t){ return new When<T>(); } static T mock(Class<T> t); static When<T> when(T t); }### Answer:
@Test public void testStub(){ when(mockList.get(0)).thenReturn(1); System.out.println(mockList.get(0)); }
@Test public void testArgsMatch(){ when(mockList.get(anyInt())).thenReturn("Hello Chubin"); when(mockList.contains(argThat(new Contains("Chubin")))).thenReturn(true); assertEquals(mockList.get(1), "Hello Chubin"); assertTrue(mockList.contains("Chubin")); verify(mockList).get(anyInt()); }
@Test public void testException(){ when(mockList.get(Integer.MAX_VALUE)).thenThrow(new ArrayIndexOutOfBoundsException("下标越界!")); System.out.println(mockList.get(Integer.MAX_VALUE)); }
@Test public void testCallBack(){ when(mockList.get(Integer.MAX_VALUE)).thenAnswer(invocation -> { Object mock = invocation.getMock(); Object[] arguments = invocation.getArguments(); return new StringBuilder().append(mock).append(",").append(Arrays.asList(arguments)).toString(); }); System.out.println(mockList.get(Integer.MAX_VALUE)); verify(mockList).get(Integer.MAX_VALUE); } |
### Question:
Mockito { public static <T> T mock(Class<T> t){ Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t); enhancer.setCallback(new MockMethodInterceptor()); return (T) enhancer.create(); } static T mock(Class<T> t); static When<T> when(T t); }### Answer:
@Test public void testOrder(){ List simpleList1 = mock(List.class); List simpleList2 = mock(List.class); simpleList1.add("first call"); simpleList2.add("second call"); InOrder inOrder = inOrder(simpleList1, simpleList2); inOrder.verify(simpleList1).add("first call"); inOrder.verify(simpleList2).add("second call"); } |
### Question:
LogController { @RequestMapping("/now/{id}") @ResponseBody public LocalDateTime now(@PathVariable String id, HttpServletRequest request) { mdcThreadPool.execute(new Runnable() { @Override public void run() { MDC.put("traceId", request.getRequestURI()); logger.info("线程池任务执行-------1"); } }); logger.info("mdc context:{}", MDC.getCopyOfContextMap()); return LocalDateTime.now(); } @RequestMapping("/now/{id}") @ResponseBody LocalDateTime now(@PathVariable String id, HttpServletRequest request); @RequestMapping("/test/{id}") @ResponseBody String test(@PathVariable String id, HttpServletRequest request); @RequestMapping("/java/{id}") @ResponseBody String java(@PathVariable String id, HttpServletRequest request); @RequestMapping("/mdc/{id}") @ResponseBody String mdcController(@PathVariable String id, HttpServletRequest request); }### Answer:
@Test public void now() throws Exception { ResultActions resultActions = this.mvc.perform(new RequestBuilder() { @Override public MockHttpServletRequest buildRequest(ServletContext servletContext) { return new MockHttpServletRequest(RequestMethod.GET.name(), "/now/1"); } }).andExpect(status().isOk()); String contentAsString = resultActions.andReturn().getResponse().getContentAsString(); assertNotNull(contentAsString); } |
### Question:
MessagingAccessPointAdapter { public static MessagingAccessPoint getMessagingAccessPoint(String url, KeyValue attributes) { AccessPointURI accessPointURI = new AccessPointURI(url); String driverImpl = parseDriverImpl(accessPointURI.getDriverType(), attributes); attributes.put(OMSBuiltinKeys.ACCESS_POINTS, accessPointURI.getHosts()); attributes.put(OMSBuiltinKeys.DRIVER_IMPL, driverImpl); attributes.put(OMSBuiltinKeys.REGION, accessPointURI.getRegion()); attributes.put(OMSBuiltinKeys.ACCOUNT_ID, accessPointURI.getAccountId()); try { Class<?> driverImplClass = Class.forName(driverImpl); Constructor constructor = driverImplClass.getConstructor(KeyValue.class); MessagingAccessPoint vendorImpl = (MessagingAccessPoint) constructor.newInstance(attributes); checkSpecVersion(OMS.specVersion, vendorImpl.version()); return vendorImpl; } catch (Throwable e) { throw generateException(OMSResponseStatus.STATUS_10000, url); } } static MessagingAccessPoint getMessagingAccessPoint(String url, KeyValue attributes); }### Answer:
@Test public void getMessagingAccessPoint() { String testURI = "oms:test-vendor: KeyValue keyValue = OMS.newKeyValue(); keyValue.put(OMSBuiltinKeys.DRIVER_IMPL, "io.openmessaging.internal.TestVendor"); MessagingAccessPoint messagingAccessPoint = OMS.getMessagingAccessPoint(testURI, keyValue); assertThat(messagingAccessPoint).isExactlyInstanceOf(TestVendor.class); } |
### Question:
DefaultKeyValue implements KeyValue { @Override public Set<String> keySet() { return properties.keySet(); } DefaultKeyValue(); @Override KeyValue put(String key, boolean value); @Override boolean getBoolean(String key); @Override boolean getBoolean(String key, boolean defaultValue); @Override short getShort(String key); @Override short getShort(String key, short defaultValue); @Override KeyValue put(String key, short value); @Override KeyValue put(String key, int value); @Override KeyValue put(String key, long value); @Override KeyValue put(String key, double value); @Override KeyValue put(String key, String value); @Override int getInt(String key); @Override int getInt(final String key, final int defaultValue); @Override long getLong(String key); @Override long getLong(final String key, final long defaultValue); @Override double getDouble(String key); @Override double getDouble(final String key, final double defaultValue); @Override String getString(String key); @Override String getString(final String key, final String defaultValue); @Override Set<String> keySet(); @Override boolean containsKey(String key); }### Answer:
@Test public void testKeySet() throws Exception { keyValue.put("IndexKey", 123); assertThat(keyValue.keySet()).contains("IndexKey"); } |
### Question:
DefaultKeyValue implements KeyValue { @Override public boolean containsKey(String key) { return properties.containsKey(key); } DefaultKeyValue(); @Override KeyValue put(String key, boolean value); @Override boolean getBoolean(String key); @Override boolean getBoolean(String key, boolean defaultValue); @Override short getShort(String key); @Override short getShort(String key, short defaultValue); @Override KeyValue put(String key, short value); @Override KeyValue put(String key, int value); @Override KeyValue put(String key, long value); @Override KeyValue put(String key, double value); @Override KeyValue put(String key, String value); @Override int getInt(String key); @Override int getInt(final String key, final int defaultValue); @Override long getLong(String key); @Override long getLong(final String key, final long defaultValue); @Override double getDouble(String key); @Override double getDouble(final String key, final double defaultValue); @Override String getString(String key); @Override String getString(final String key, final String defaultValue); @Override Set<String> keySet(); @Override boolean containsKey(String key); }### Answer:
@Test public void testContainsKey() throws Exception { keyValue.put("ContainsKey", 123); assertThat(keyValue.containsKey("ContainsKey")).isTrue(); } |
### Question:
AccessPointURI { public String getAccessPointString() { return accessPointString; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); }### Answer:
@Test public void testGetAccessPointString() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getAccessPointString()).isEqualTo(fullSchemaURI); } |
### Question:
AccessPointURI { public String getDriverType() { return driverType; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); }### Answer:
@Test public void testGetDriverType() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getDriverType()).isEqualTo("rocketmq"); } |
### Question:
AccessPointURI { public String getAccountId() { return accountId; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); }### Answer:
@Test public void testGetAccountId() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getAccountId()).isEqualTo("alice"); } |
### Question:
AccessPointURI { public String getHosts() { return hosts; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); }### Answer:
@Test public void testGetHosts() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getHosts()).isEqualTo("rocketmq.apache.org"); String multipleHostsURI = "oms:rocketmq: accessPointURI = new AccessPointURI(multipleHostsURI); assertThat(accessPointURI.getHosts()).isEqualTo("rocketmq.apache.org,pulsar.apache.org:9091"); } |
### Question:
AccessPointURI { public String getRegion() { return region; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); }### Answer:
@Test public void testGetRegion() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getRegion()).isEqualTo("us-east"); } |
### Question:
TwitterMessageProducer extends MessageProducerSupport { StatusListener getStatusListener() { return statusListener; } TwitterMessageProducer(TwitterStream twitterStream, MessageChannel outputChannel); @Override void doStart(); @Override void doStop(); void setFollows(List<Long> follows); void setTerms(List<String> terms); }### Answer:
@Test public void shouldReceiveStatus() { StatusListener statusListener = twitterMessageProducer.getStatusListener(); Status status = mock(Status.class); statusListener.onStatus(status); Message<?> statusMessage = outputChannel.receive(); assertSame(status, statusMessage.getPayload()); } |
### Question:
IndexWriter implements Stoppable { public static IndexCommitter getCommitter(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexCommitter committer = conf.getClass(INDEX_COMMITTER_CONF_KEY, ParallelWriterIndexCommitter.class, IndexCommitter.class).newInstance(); return committer; } catch (InstantiationException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } } IndexWriter(RegionCoprocessorEnvironment env, String name); IndexWriter(IndexCommitter committer, IndexFailurePolicy policy,
RegionCoprocessorEnvironment env, String name); IndexWriter(IndexCommitter committer, IndexFailurePolicy policy); static IndexCommitter getCommitter(RegionCoprocessorEnvironment env); static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env); void writeAndKillYourselfOnFailure(Collection<Pair<Mutation, byte[]>> indexUpdates,
boolean allowLocalUpdates); void writeAndKillYourselfOnFailure(Multimap<HTableInterfaceReference, Mutation> toWrite,
boolean allowLocalUpdates); void write(Collection<Pair<Mutation, byte[]>> toWrite); void write(Collection<Pair<Mutation, byte[]>> toWrite, boolean allowLocalUpdates); void write(Multimap<HTableInterfaceReference, Mutation> toWrite, boolean allowLocalUpdates); @Override void stop(String why); @Override boolean isStopped(); static final String INDEX_FAILURE_POLICY_CONF_KEY; }### Answer:
@Test public void getDefaultWriter() throws Exception { Configuration conf = new Configuration(false); RegionCoprocessorEnvironment env = Mockito.mock(RegionCoprocessorEnvironment.class); Mockito.when(env.getConfiguration()).thenReturn(conf); assertNotNull(IndexWriter.getCommitter(env)); } |
### Question:
IndexWriter implements Stoppable { public static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexFailurePolicy committer = conf.getClass(INDEX_FAILURE_POLICY_CONF_KEY, KillServerOnFailurePolicy.class, IndexFailurePolicy.class).newInstance(); return committer; } catch (InstantiationException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } } IndexWriter(RegionCoprocessorEnvironment env, String name); IndexWriter(IndexCommitter committer, IndexFailurePolicy policy,
RegionCoprocessorEnvironment env, String name); IndexWriter(IndexCommitter committer, IndexFailurePolicy policy); static IndexCommitter getCommitter(RegionCoprocessorEnvironment env); static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env); void writeAndKillYourselfOnFailure(Collection<Pair<Mutation, byte[]>> indexUpdates,
boolean allowLocalUpdates); void writeAndKillYourselfOnFailure(Multimap<HTableInterfaceReference, Mutation> toWrite,
boolean allowLocalUpdates); void write(Collection<Pair<Mutation, byte[]>> toWrite); void write(Collection<Pair<Mutation, byte[]>> toWrite, boolean allowLocalUpdates); void write(Multimap<HTableInterfaceReference, Mutation> toWrite, boolean allowLocalUpdates); @Override void stop(String why); @Override boolean isStopped(); static final String INDEX_FAILURE_POLICY_CONF_KEY; }### Answer:
@Test public void getDefaultFailurePolicy() throws Exception { Configuration conf = new Configuration(false); RegionCoprocessorEnvironment env = Mockito.mock(RegionCoprocessorEnvironment.class); Mockito.when(env.getConfiguration()).thenReturn(conf); assertNotNull(IndexWriter.getFailurePolicy(env)); } |
### Question:
OrderedResultIterator implements PeekingResultIterator { @Override public void close() throws SQLException { if (null != resultIterator) { resultIterator.close(); } resultIterator = PeekingResultIterator.EMPTY_ITERATOR; } OrderedResultIterator(ResultIterator delegate, List<OrderByExpression> orderByExpressions,
int thresholdBytes, Integer limit, Integer offset); OrderedResultIterator(ResultIterator delegate, List<OrderByExpression> orderByExpressions,
int thresholdBytes); OrderedResultIterator(ResultIterator delegate, List<OrderByExpression> orderByExpressions,
int thresholdBytes, Integer limit, Integer offset,int estimatedRowSize); Integer getLimit(); long getEstimatedByteSize(); long getByteSize(); @Override Tuple next(); @Override Tuple peek(); @Override void close(); @Override void explain(List<String> planSteps); @Override String toString(); }### Answer:
@Test public void testNullIteratorOnClose() throws SQLException { ResultIterator delegate = ResultIterator.EMPTY_ITERATOR; List<OrderByExpression> orderByExpressions = Collections.singletonList(null); int thresholdBytes = Integer.MAX_VALUE; OrderedResultIterator iterator = new OrderedResultIterator(delegate, orderByExpressions, thresholdBytes); iterator.close(); } |
### Question:
CsvBulkImportUtil { @VisibleForTesting static Character getCharacter(Configuration conf, String confKey) { String strValue = conf.get(confKey); if (strValue == null) { return null; } return new String(Base64.decode(strValue)).charAt(0); } static void initCsvImportJob(Configuration conf, char fieldDelimiter, char quoteChar,
char escapeChar, String arrayDelimiter, String binaryEncoding); static void configurePreUpsertProcessor(Configuration conf,
Class<? extends ImportPreUpsertKeyValueProcessor> processorClass); static Path getOutputPath(Path outputdir, String tableName); }### Answer:
@Test public void testGetChar_NotPresent() { Configuration conf = new Configuration(); assertNull(CsvBulkImportUtil.getCharacter(conf, "conf.key")); } |
### Question:
ResourceList { Collection<String> getResourcesFromJarFile( final File file, final Pattern pattern) { final List<String> retVal = new ArrayList<>(); ZipFile zf; try { zf = new ZipFile(file); } catch (FileNotFoundException e) { return Collections.emptyList(); } catch (final ZipException e) { throw new Error(e); } catch (final IOException e) { throw new Error(e); } final Enumeration e = zf.entries(); while (e.hasMoreElements()) { final ZipEntry ze = (ZipEntry) e.nextElement(); final String fileName = ze.getName(); final boolean accept = pattern.matcher(fileName).matches(); logger.trace("fileName:" + fileName); logger.trace("File:" + file.toString()); logger.trace("Match:" + accept); if (accept) { logger.trace("Adding File from Jar: " + fileName); retVal.add("/" + fileName); } } try { zf.close(); } catch (final IOException e1) { throw new Error(e1); } return retVal; } ResourceList(String rootResourceDir); Collection<Path> getResourceList(final String pattern); }### Answer:
@Test public void testMissingJarFileReturnsGracefully() { ResourceList rl = new ResourceList("foo"); File missingFile = new File("abracadabraphoenix.txt"); assertFalse("Did not expect a fake test file to actually exist", missingFile.exists()); assertEquals(Collections.emptyList(), rl.getResourcesFromJarFile(missingFile, Pattern.compile("pattern"))); } |
### Question:
Pherf { public static void main(String[] args) { try { new Pherf(args).run(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } Pherf(String[] args); static void main(String[] args); void run(); }### Answer:
@Test public void testListArgument() { String[] args = {"-listFiles"}; Pherf.main(args); }
@Test public void testUnknownOption() { String[] args = {"-drop", "all", "-q", "-m","-bsOption"}; exit.expectSystemExitWithStatus(1); Pherf.main(args); } |
### Question:
StatisticsScanner implements InternalScanner { @Override public void close() throws IOException { boolean async = getConfig().getBoolean(COMMIT_STATS_ASYNC, DEFAULT_COMMIT_STATS_ASYNC); StatisticsCollectionRunTracker collectionTracker = getStatsCollectionRunTracker(config); StatisticsScannerCallable callable = createCallable(); if (getRegionServerServices().isStopping() || getRegionServerServices().isStopped()) { LOG.debug("Not updating table statistics because the server is stopping/stopped"); return; } if (!async) { callable.call(); } else { collectionTracker.runTask(callable); } } StatisticsScanner(StatisticsCollector tracker, StatisticsWriter stats, RegionCoprocessorEnvironment env,
InternalScanner delegate, ImmutableBytesPtr family); @Override boolean next(List<Cell> result); @Override boolean next(List<Cell> result, ScannerContext scannerContext); @Override void close(); }### Answer:
@Test public void testCheckRegionServerStoppingOnClose() throws Exception { when(rsServices.isStopping()).thenReturn(true); when(rsServices.isStopped()).thenReturn(false); mockScanner.close(); verify(rsServices).isStopping(); verify(callable, never()).call(); verify(runTracker, never()).runTask(callable); }
@Test public void testCheckRegionServerStoppedOnClose() throws Exception { when(rsServices.isStopping()).thenReturn(false); when(rsServices.isStopped()).thenReturn(true); mockScanner.close(); verify(rsServices).isStopping(); verify(rsServices).isStopped(); verify(callable, never()).call(); verify(runTracker, never()).runTask(callable); } |
### Question:
PropertiesUtil { public static Properties extractProperties(Properties props, final Configuration conf) { Iterator<Map.Entry<String, String>> iterator = conf.iterator(); if(iterator != null) { while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); props.setProperty(entry.getKey(), entry.getValue()); } } return props; } private PropertiesUtil(); static Properties deepCopy(Properties properties); static Properties extractProperties(Properties props, final Configuration conf); }### Answer:
@Test public void testCopyFromConfiguration() throws Exception{ final Configuration conf = HBaseConfiguration.create(); final Properties props = new Properties(); conf.set(HConstants.ZOOKEEPER_QUORUM, HConstants.LOCALHOST); conf.set(PropertiesUtilTest.SOME_OTHER_PROPERTY_KEY, PropertiesUtilTest.SOME_OTHER_PROPERTY_VALUE); PropertiesUtil.extractProperties(props, conf); assertEquals(props.getProperty(HConstants.ZOOKEEPER_QUORUM), conf.get(HConstants.ZOOKEEPER_QUORUM)); assertEquals(props.getProperty(PropertiesUtilTest.SOME_OTHER_PROPERTY_KEY), conf.get(PropertiesUtilTest.SOME_OTHER_PROPERTY_KEY)); } |
### Question:
JDBCUtil { public static Consistency getConsistencyLevel(String url, Properties info, String defaultValue) { String consistency = findProperty(url, info, PhoenixRuntime.CONSISTENCY_ATTRIB); if(consistency != null && consistency.equalsIgnoreCase(Consistency.TIMELINE.toString())){ return Consistency.TIMELINE; } return Consistency.STRONG; } private JDBCUtil(); static String findProperty(String url, Properties info, String propName); static String removeProperty(String url, String propName); static Map<String, String> getAnnotations(@NotNull String url, @NotNull Properties info); static Long getCurrentSCN(String url, Properties info); @Deprecated // use getMutateBatchSizeBytes static int getMutateBatchSize(String url, Properties info, ReadOnlyProps props); static long getMutateBatchSizeBytes(String url, Properties info, ReadOnlyProps props); static @Nullable PName getTenantId(String url, Properties info); static boolean getAutoCommit(String url, Properties info, boolean defaultValue); static Consistency getConsistencyLevel(String url, Properties info, String defaultValue); static boolean isCollectingRequestLevelMetricsEnabled(String url, Properties overrideProps, ReadOnlyProps queryServicesProps); static String getSchema(String url, Properties info, String defaultValue); }### Answer:
@Test public void testGetConsistency_TIMELINE_InUrl() { assertTrue(JDBCUtil.getConsistencyLevel("localhost;Consistency=TIMELINE", new Properties(), Consistency.STRONG.toString()) == Consistency.TIMELINE); }
@Test public void testGetConsistency_TIMELINE_InProperties() { Properties props = new Properties(); props.setProperty(PhoenixRuntime.CONSISTENCY_ATTRIB, "TIMELINE"); assertTrue(JDBCUtil.getConsistencyLevel("localhost", props, Consistency.STRONG.toString()) == Consistency.TIMELINE); } |
### Question:
JDBCUtil { public static String getSchema(String url, Properties info, String defaultValue) { String schema = findProperty(url, info, PhoenixRuntime.SCHEMA_ATTRIB); return (schema == null || schema.equals("")) ? defaultValue : schema; } private JDBCUtil(); static String findProperty(String url, Properties info, String propName); static String removeProperty(String url, String propName); static Map<String, String> getAnnotations(@NotNull String url, @NotNull Properties info); static Long getCurrentSCN(String url, Properties info); @Deprecated // use getMutateBatchSizeBytes static int getMutateBatchSize(String url, Properties info, ReadOnlyProps props); static long getMutateBatchSizeBytes(String url, Properties info, ReadOnlyProps props); static @Nullable PName getTenantId(String url, Properties info); static boolean getAutoCommit(String url, Properties info, boolean defaultValue); static Consistency getConsistencyLevel(String url, Properties info, String defaultValue); static boolean isCollectingRequestLevelMetricsEnabled(String url, Properties overrideProps, ReadOnlyProps queryServicesProps); static String getSchema(String url, Properties info, String defaultValue); }### Answer:
@Test public void testSchema() { assertTrue(JDBCUtil.getSchema("localhost;schema=TEST", new Properties(), null).equals("TEST")); assertNull(JDBCUtil.getSchema("localhost;schema=", new Properties(), null)); assertNull(JDBCUtil.getSchema("localhost;", new Properties(), null)); } |
### Question:
DateUtil { public static Date parseDate(String dateValue) { return new Date(parseDateTime(dateValue)); } private DateUtil(); @NotNull static PDataCodec getCodecFor(PDataType type); static TimeZone getTimeZone(String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType, String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType); static Format getDateFormatter(String pattern); static Format getTimeFormatter(String pattern); static Format getTimestampFormatter(String pattern); static Date parseDate(String dateValue); static Time parseTime(String timeValue); static Timestamp parseTimestamp(String timestampValue); static Timestamp getTimestamp(long millis, int nanos); static Timestamp getTimestamp(BigDecimal bd); static final String DEFAULT_TIME_ZONE_ID; static final String LOCAL_TIME_ZONE_ID; static final String DEFAULT_MS_DATE_FORMAT; static final Format DEFAULT_MS_DATE_FORMATTER; static final String DEFAULT_DATE_FORMAT; static final Format DEFAULT_DATE_FORMATTER; static final String DEFAULT_TIME_FORMAT; static final Format DEFAULT_TIME_FORMATTER; static final String DEFAULT_TIMESTAMP_FORMAT; static final Format DEFAULT_TIMESTAMP_FORMATTER; }### Answer:
@Test public void testParseDate() { assertEquals(10000L, DateUtil.parseDate("1970-01-01 00:00:10").getTime()); }
@Test public void testParseDate_PureDate() { assertEquals(0L, DateUtil.parseDate("1970-01-01").getTime()); }
@Test(expected = IllegalDataException.class) public void testParseDate_InvalidDate() { DateUtil.parseDate("not-a-date"); }
@Test(expected=IllegalDataException.class) public void testParseTime_InvalidTime() { DateUtil.parseDate("not-a-time"); } |
### Question:
DateUtil { public static Time parseTime(String timeValue) { return new Time(parseDateTime(timeValue)); } private DateUtil(); @NotNull static PDataCodec getCodecFor(PDataType type); static TimeZone getTimeZone(String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType, String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType); static Format getDateFormatter(String pattern); static Format getTimeFormatter(String pattern); static Format getTimestampFormatter(String pattern); static Date parseDate(String dateValue); static Time parseTime(String timeValue); static Timestamp parseTimestamp(String timestampValue); static Timestamp getTimestamp(long millis, int nanos); static Timestamp getTimestamp(BigDecimal bd); static final String DEFAULT_TIME_ZONE_ID; static final String LOCAL_TIME_ZONE_ID; static final String DEFAULT_MS_DATE_FORMAT; static final Format DEFAULT_MS_DATE_FORMATTER; static final String DEFAULT_DATE_FORMAT; static final Format DEFAULT_DATE_FORMATTER; static final String DEFAULT_TIME_FORMAT; static final Format DEFAULT_TIME_FORMATTER; static final String DEFAULT_TIMESTAMP_FORMAT; static final Format DEFAULT_TIMESTAMP_FORMATTER; }### Answer:
@Test public void testParseTime() { assertEquals(10000L, DateUtil.parseTime("1970-01-01 00:00:10").getTime()); } |
### Question:
EmailValidator { public static boolean isValidEmail(CharSequence email) { return email != null && EMAIL_PATTERN.matcher(email).matches(); } static boolean isValidEmail(CharSequence email); static final Pattern EMAIL_PATTERN; }### Answer:
@Test public void isValidEmail() throws Exception { assertThat(EmailValidator.isValidEmail("[email protected]")).isTrue(); } |
### Question:
SampleService { public static boolean start() { return true; } static boolean start(); }### Answer:
@Test public void onStartCommand() throws Exception { assertThat(SampleService.start()).isTrue(); } |
### Question:
Calculator { public static double add(int firstOperand, double secondOperand) { return firstOperand + secondOperand; } static double add(int firstOperand, double secondOperand); }### Answer:
@Test public void add() throws Exception { assertThat(Calculator.add(1, 2)).isEqualTo(3); } |
### Question:
BridgeServiceImpl implements BridgeService { @Override public BridgeDTO create(BridgeCreateDTO bridge) throws InvalidIpException, BridgeAlreadyExistsException, UserDoesNotExistException { if (!isIPv4Address(bridge.getIp())) { throw new InvalidIpException(bridge.getIp()); } else if (bridgeRepository.findByIp(bridge.getIp()) != null) { throw new BridgeAlreadyExistsException(bridge.getIp()); } User user = userRepository.findOne(bridge.getUserId()); if (user == null) { throw new UserDoesNotExistException(bridge.getUserId()); } Bridge b = new Bridge(); b.setIp(bridge.getIp()); b.setUser(user); b = bridgeRepository.save(b); BridgeDTO dto = mapper.map(b, BridgeDTO.class); hueService.connectToBridgeIfNotAlreadyConnected(dto); return dto; } @Autowired BridgeServiceImpl(UserRepository userRepository, BridgeRepository bridgeRepository, HueService hueService, Mapper mapper); @Override List<BridgeDTO> findAll(); @Override List<BridgeDTO> findAll(int page, int size); @Override List<FoundBridgeDTO> findAvailable(); @Override long count(); @Override List<BridgeDTO> findBySearchItem(String searchItem); @Override List<BridgeDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override BridgeDTO create(BridgeCreateDTO bridge); @Override BridgeDTO findByIp(String ip); @Override void remove(long id); }### Answer:
@Test(expected = InvalidIpException.class) public void testCreateWithInvalidIp() { bridgeService.create(new BridgeCreateDTO("invalid", -1)); fail(); }
@Test(expected = UserDoesNotExistException.class) public void testCreateWithoutValidUserId() { bridgeService.create(new BridgeCreateDTO("127.0.0.1", -1)); fail(); } |
### Question:
LampServiceImpl implements LampService { @Override public LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp) throws LampDoesNotExistsException { Lamp l = lampRepository.findOne(lamp.getId()); if (l != null) { l.setLastShownScenario(lamp.getLastShownScenario()); l = lampRepository.save(l); return mapper.map(l, LampDTO.class); } else { throw new LampDoesNotExistsException(lamp.getId()); } } @Autowired LampServiceImpl(LampRepository lampRepository, TeamRepository teamRepository, HueService hueService, HolidayService holidayService, Mapper mapper); @Override LampDTO create(LampCreateDTO lamp); @Override LampDTO update(LampUpdateDTO lamp); @Override LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp); @Override LampDTO rename(LampRenameDTO lamp); @Override void remove(long id); @Override List<LampDTO> findAll(); @Override LampGroupedScenariosDTO findOne(long id); @Override long count(); @Override long count(long teamId); @Override List<LampHueDTO> findAllAvailable(); @Override TeamLampsDTO findAllOfATeam(long teamId); @Override List<LampNameDTO> findAllLampNamesOfATeam(long teamId); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); }### Answer:
@Test(expected = LampDoesNotExistsException.class) public void testUpdateLastShownScenarioWithoutValidLampId() { lampService.updateLastShownScenario(new LampUpdateLastShownScenarioDTO(-1, Scenario.BUILDING)); fail(); } |
### Question:
LampServiceImpl implements LampService { @Override public LampDTO rename(LampRenameDTO lamp) throws EmptyInputException, LampDoesNotExistsException { if (lamp.getName() == null || lamp.getName().trim().isEmpty()) { throw new EmptyInputException(); } Lamp l = lampRepository.findOne(lamp.getId()); if (l != null) { l.setName(lamp.getName()); l = lampRepository.save(l); return mapper.map(l, LampDTO.class); } else { throw new LampDoesNotExistsException(lamp.getId()); } } @Autowired LampServiceImpl(LampRepository lampRepository, TeamRepository teamRepository, HueService hueService, HolidayService holidayService, Mapper mapper); @Override LampDTO create(LampCreateDTO lamp); @Override LampDTO update(LampUpdateDTO lamp); @Override LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp); @Override LampDTO rename(LampRenameDTO lamp); @Override void remove(long id); @Override List<LampDTO> findAll(); @Override LampGroupedScenariosDTO findOne(long id); @Override long count(); @Override long count(long teamId); @Override List<LampHueDTO> findAllAvailable(); @Override TeamLampsDTO findAllOfATeam(long teamId); @Override List<LampNameDTO> findAllLampNamesOfATeam(long teamId); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); }### Answer:
@Test(expected = EmptyInputException.class) public void testRenameWithEmptyInput() { try { lampService.rename(new LampRenameDTO(-1, null)); } catch (EmptyInputException eie) { lampService.rename(new LampRenameDTO(-1, "")); } fail(); }
@Test(expected = LampDoesNotExistsException.class) public void testRenameWithInvalidLampId() { lampService.rename(new LampRenameDTO(-1, "Lamp 1")); fail(); } |
### Question:
LampServiceImpl implements LampService { @Override public TeamLampsDTO findAllOfATeam(long teamId) throws TeamDoesNotExistException { Team team = teamRepository.findOne(teamId); if (team != null) { TeamLampsDTO dto = mapper.map(team, TeamLampsDTO.class); for (int i = 0; i < nullSafe(team.getLamps()).size(); i++) { TeamLampsDTO.TeamLampsDTO_LampDTO lampDTO = dto.getLamps().get(i); setGroupedScenarioConfigs(lampDTO, team.getLamps().get(i).getScenarioConfigs()); } return dto; } else { throw new TeamDoesNotExistException(teamId); } } @Autowired LampServiceImpl(LampRepository lampRepository, TeamRepository teamRepository, HueService hueService, HolidayService holidayService, Mapper mapper); @Override LampDTO create(LampCreateDTO lamp); @Override LampDTO update(LampUpdateDTO lamp); @Override LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp); @Override LampDTO rename(LampRenameDTO lamp); @Override void remove(long id); @Override List<LampDTO> findAll(); @Override LampGroupedScenariosDTO findOne(long id); @Override long count(); @Override long count(long teamId); @Override List<LampHueDTO> findAllAvailable(); @Override TeamLampsDTO findAllOfATeam(long teamId); @Override List<LampNameDTO> findAllLampNamesOfATeam(long teamId); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); }### Answer:
@Test(expected = TeamDoesNotExistException.class) public void testFindAllOfATeamWithoutValidTeamId() { lampService.findAllOfATeam(-1); fail(); } |
### Question:
UserServiceImpl implements UserService { @Override public UserDTO update(UserUpdateDTO user) throws UserDoesNotExistException { User userInDB = userRepository.findOne(user.getId()); if (userInDB == null) { throw new UserDoesNotExistException(user.getId()); } userInDB.setRoles(user.getRoles()); userInDB = userRepository.save(userInDB); return mapper.map(userInDB, UserDTO.class); } @Autowired UserServiceImpl(TeamRepository teamRepository, UserRepository userRepository, BridgeRepository bridgeRepository, Mapper mapper); @Override List<UserDTO> findAll(); @Override List<UserDTO> findAll(int page, int size); @Override long count(); @Override List<UserDTO> findBySearchItem(String searchItem); @Override List<UserDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override long count(long teamId); @Override UserDTO create(UserCreateDTO user); @Override UserDTO update(UserUpdateDTO user); @Override void remove(long id); @Override UserDTO findByLogin(String login); }### Answer:
@Test(expected = UserDoesNotExistException.class) public void testUpdateUserWithoutValidId() { userService.update(new UserUpdateDTO(-1, null)); fail(); } |
### Question:
TeamServiceImpl implements TeamService { @Override public TeamUsersDTO update(TeamUpdateDTO team) throws TeamDoesNotExistException { Team teamInDB = teamRepository.findOne(team.getId()); if(teamInDB == null) { throw new TeamDoesNotExistException(team.getId()); } else { if(team.getScenarioPriority() != null && team.getScenarioPriority().size() == Scenario.getPriorityListLength()) { teamInDB.setScenarioPriority(team.getScenarioPriority()); teamInDB = teamRepository.save(teamInDB); return mapper.map(teamInDB, TeamUsersDTO.class); } else { throw new IllegalArgumentException("Die priorisierte Liste enthält nicht alle Szenarios!"); } } } @Autowired TeamServiceImpl(TeamRepository teamRepository, UserRepository userRepository, BridgeRepository bridgeRepository, Mapper mapper); @Override List<TeamUsersDTO> findAll(); @Override List<TeamUsersDTO> findAll(int page, int size); @Override long count(); @Override List<TeamUsersDTO> findBySearchItem(String searchItem); @Override List<TeamUsersDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override TeamLampsDTO create(TeamCreateDTO team); @Override TeamUsersDTO update(TeamUpdateDTO team); @Override TeamUsersDTO rename(TeamRenameDTO team); @Override TeamUsersDTO findOne(long id); @Override void remove(long id); }### Answer:
@Test(expected = TeamDoesNotExistException.class) public void testUpdateTeamWithoutValidId() { teamService.update(new TeamUpdateDTO(-1, null)); fail(); } |
### Question:
TeamServiceImpl implements TeamService { @Override public TeamUsersDTO rename(TeamRenameDTO team) throws TeamDoesNotExistException, TeamAlreadyExistsException, EmptyInputException { Team t = teamRepository.findOne(team.getId()); if(t != null) { if(team.getName() == null || team.getName().trim().isEmpty()) { throw new EmptyInputException(); } else if(t.getName().equals(team.getName())) { return mapper.map(t, TeamUsersDTO.class); } Team teamWithSameName = teamRepository.findByName(team.getName()); if(teamWithSameName == null) { t.setName(team.getName()); teamRepository.save(t); return mapper.map(t, TeamUsersDTO.class); } else { throw new TeamAlreadyExistsException(team.getName()); } } else { throw new TeamDoesNotExistException(team.getId()); } } @Autowired TeamServiceImpl(TeamRepository teamRepository, UserRepository userRepository, BridgeRepository bridgeRepository, Mapper mapper); @Override List<TeamUsersDTO> findAll(); @Override List<TeamUsersDTO> findAll(int page, int size); @Override long count(); @Override List<TeamUsersDTO> findBySearchItem(String searchItem); @Override List<TeamUsersDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override TeamLampsDTO create(TeamCreateDTO team); @Override TeamUsersDTO update(TeamUpdateDTO team); @Override TeamUsersDTO rename(TeamRenameDTO team); @Override TeamUsersDTO findOne(long id); @Override void remove(long id); }### Answer:
@Test(expected = TeamDoesNotExistException.class) public void testRenameTeamWithoutValidId() { teamService.rename(new TeamRenameDTO(-1, "Team 2")); fail(); } |
### Question:
HueServiceImpl implements HueService { @Override public boolean ipAreEqual(String ip1, String ip2) { return removePortAndToLowerCase(ip1).equals(removePortAndToLowerCase(ip2)); } @Autowired HueServiceImpl(BridgeRepository bridgeRepository); @PostConstruct void init(); @PreDestroy void destroy(); void initListener(); @Override void connectToBridgeIfNotAlreadyConnected(BridgeDTO bridge); @Override void disconnectFromBridge(BridgeDTO bridge); @Override void showRandomColorsOnAllLamps(); @Async @Override void updateLamp(LampWithHueUniqueId lamp, ScenarioConfigDTO config); @Override List<LampHueDTO> findAllLamps(); @Override List<FoundBridgeDTO> findAllBridges(); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); @Override void updateBridgeState(List<BridgeDTO> bridgeDTOs); @Override boolean ipAreEqual(String ip1, String ip2); String removePortAndToLowerCase(String ip); }### Answer:
@Test public void testIpAreEqual() { String ip1 = "10.10.10.10"; String ip2 = "10.10.10.10:80"; String ip3 = "10.10.10.20:80"; String ip4 = "10.10.10.20:45"; assertTrue(hueService.ipAreEqual(ip1, ip2)); assertFalse(hueService.ipAreEqual(ip2, ip3)); assertTrue(hueService.ipAreEqual(ip3, ip4)); } |
### Question:
HueServiceImpl implements HueService { @Override public List<FoundBridgeDTO> findAllBridges() { return new ArrayList<>(Arrays.asList(new TestRestTemplate().getForObject("https: } @Autowired HueServiceImpl(BridgeRepository bridgeRepository); @PostConstruct void init(); @PreDestroy void destroy(); void initListener(); @Override void connectToBridgeIfNotAlreadyConnected(BridgeDTO bridge); @Override void disconnectFromBridge(BridgeDTO bridge); @Override void showRandomColorsOnAllLamps(); @Async @Override void updateLamp(LampWithHueUniqueId lamp, ScenarioConfigDTO config); @Override List<LampHueDTO> findAllLamps(); @Override List<FoundBridgeDTO> findAllBridges(); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); @Override void updateBridgeState(List<BridgeDTO> bridgeDTOs); @Override boolean ipAreEqual(String ip1, String ip2); String removePortAndToLowerCase(String ip); }### Answer:
@Test public void testFindAllBridgesIsModifiable() { List<FoundBridgeDTO> allBridges = hueService.findAllBridges(); allBridges.add(new FoundBridgeDTO()); allBridges.add(new FoundBridgeDTO()); allBridges.remove(0); } |
### Question:
JobListener { BuildState extractBuildState(JenkinsBuildDTO build) { if (build == null) { throw new IllegalArgumentException("build ist null!"); } else { if (build.isBuilding()) { return BuildState.BUILDING; } else { return BuildState.valueOf(build.getResult()); } } } @Autowired JobListener(JenkinsService jenkinsService, LampService lampService, HueService hueService); }### Answer:
@Test public void testExtractBuildState() { JenkinsBuildDTO b1 = new JenkinsBuildDTO(false, "FAILURE", 1, null); JenkinsBuildDTO b2 = new JenkinsBuildDTO(false, "UNSTABLE", 2, null); JenkinsBuildDTO b3 = new JenkinsBuildDTO(false, "SUCCESS", 3, null); JenkinsBuildDTO b4 = new JenkinsBuildDTO(true, "", 4, null); assertEquals(BuildState.FAILURE, jobListener.extractBuildState(b1)); assertEquals(BuildState.UNSTABLE, jobListener.extractBuildState(b2)); assertEquals(BuildState.SUCCESS, jobListener.extractBuildState(b3)); assertEquals(BuildState.BUILDING, jobListener.extractBuildState(b4)); } |
### Question:
HolidayServiceImpl implements HolidayService { @Override public boolean isWeekend(DateTime day) { return day != null && (day.getDayOfWeek() == DateTimeConstants.SATURDAY || day.getDayOfWeek() == DateTimeConstants.SUNDAY); } @Override boolean isHoliday(DateTime day); @Override boolean isWeekend(DateTime day); @Override boolean isValidWorkingPeriod(DateTime workingStart, DateTime workingEnd); }### Answer:
@Test public void testIsWeekend() { assertFalse(holidayService.isWeekend(new DateTime(2016, 1, 1, 0, 0))); assertTrue(holidayService.isWeekend(new DateTime(2016, 1, 2, 0, 0))); assertTrue(holidayService.isWeekend(new DateTime(2016, 1, 3, 0, 0))); assertFalse(holidayService.isWeekend(new DateTime(2016, 1, 4, 0, 0))); assertFalse(holidayService.isWeekend(null)); } |
### Question:
RMSKeyUtils { int toValueIndex(final Long hashValue) { return (int) (hashValue.longValue() & 0xFFFFFFFF); } }### Answer:
@Test public void valueIndexValuesCanStoreEntireIntegerRange() { long one = 1; long previous = 0; for (int bits = 0; bits < 32; bits++) { long shifted = one << bits; assertTrue("Overflow when shifting long. Previous value: " + previous + " now: " + shifted, shifted > previous); previous = shifted; int vi = keyUtils.toValueIndex(shifted); assertEquals((int) shifted, vi); } } |
### Question:
StringUtils { public static byte[] hexStringToByteArray(final String s) { if (s == null) { throw new NullPointerException("hexStringToByteArray was pass null string"); } final int n = s.length(); if (n % 2 != 0) { throw new IllegalArgumentException("Input string must be an even length and encoded by byteArrayToHexString(s), but input length is " + n); } final byte[] bytes = new byte[n / 2]; int k = 0; for (int i = 0; i < n; i += 2) { final String substring = s.substring(i, i + 2); final int j = Integer.parseInt(substring, 16); bytes[k++] = (byte) j; } return bytes; } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String readStringFromJAR(final String name); static String readStringFromJAR(final String name, final String encoding); static String urlEncode(final String s); static String urlDecode(final String s); static String hexStringToString(final String s); static String stringToHexString(final String s); static String byteArrayToHexString(final byte[] bytes); static byte[] hexStringToByteArray(final String s); }### Answer:
@Test public void sampleBytesToHexString() { assertArrayEquals(sampleAsBytes, StringUtils.hexStringToByteArray(sampleAsHex)); }
@Test(expected = IllegalArgumentException.class) public void hexStringChecksForWrongLengthInput() { StringUtils.hexStringToByteArray("0"); }
@Test(expected = IllegalArgumentException.class) public void illegalCharsInHexStringFirstPosition() { StringUtils.hexStringToByteArray("QF"); }
@Test(expected = IllegalArgumentException.class) public void illegalCharsInHexStringSecondPosition() { StringUtils.hexStringToByteArray("FZ"); } |
### Question:
StringUtils { public static String byteArrayToHexString(final byte[] bytes) { final StringBuffer sb = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { appendHex(bytes[i], sb); } return sb.toString(); } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String readStringFromJAR(final String name); static String readStringFromJAR(final String name, final String encoding); static String urlEncode(final String s); static String urlDecode(final String s); static String hexStringToString(final String s); static String stringToHexString(final String s); static String byteArrayToHexString(final byte[] bytes); static byte[] hexStringToByteArray(final String s); }### Answer:
@Test public void sampleHexStringAsBytes() { assertEquals(sampleAsHex, StringUtils.byteArrayToHexString(sampleAsBytes)); }
@Test public void toHexTestFF00() { assertEquals("FF00", StringUtils.byteArrayToHexString(byteTest1)); }
@Test public void toHexTestCD1A() { assertEquals("CD1A", StringUtils.byteArrayToHexString(byteTest2)); } |
### Question:
RMSKeyUtils { int toKeyIndex(final Long hashValue) { return (int) ((hashValue.longValue() >>> 32) & 0xFFFFFFFF); } }### Answer:
@Test public void keyIndexValuesCanStoreEntireIntegerRange() { final int bitsInInteger = 32; final long one = 1; for (int bits = 0; bits < bitsInInteger; bits++) { final int keyIntegerValue = (int)(one << bits); final long shiftedLong = one << (bits + bitsInInteger); int ki = keyUtils.toKeyIndex(shiftedLong); assertEquals(keyIntegerValue, ki); } } |
### Question:
RMSFastCache extends FlashCache { public void removeData(final long digest) throws FlashDatabaseException { synchronized (mutex) { try { final Long indexEntry = indexHashGet(digest, false); if (indexEntry != null) { final Long dig = new Long(digest); indexHash.remove(dig); final int valueRecordId = RMSKeyUtils.toValueIndex(indexEntry); final int keyRecordId = RMSKeyUtils.toKeyIndex(indexEntry); int size = 0; if (!Task.isShuttingDown()) { try { final byte[] keyBytes = getKeyRS().getRecord(keyRecordId); final byte[] valueBytes = getValueRS().getRecord(valueRecordId); size = valueBytes.length + keyBytes.length; } catch (Exception e) { L.e(this, "removeData", "can't read", e); } } final boolean storeFlagSet = setStoreFlag(); getValueRS().deleteRecord(valueRecordId); getKeyRS().deleteRecord(keyRecordId); if (storeFlagSet) { clearStoreFlag(); } rmsByteSize -= size; } else { L.i("*** Can not remove from RMS, digest not found", "" + digest + " - " + toString()); } } catch (RecordStoreException e) { throw new FlashDatabaseException("Can not removeData from RMS: " + Long.toString(digest, 16) + " - " + e); } } } RMSFastCache(final char priority, final FlashCache.StartupTask startupTask); void markLeastRecentlyUsed(final Long digest); static void deleteDataFiles(final char priority); String getKey(final long digest); byte[] get(final long digest, final boolean markAsLeastRecentlyUsed); void put(final String key, final byte[] value); void removeData(final long digest); Enumeration getDigests(); void clear(); long getFreespace(); long getSize(); void close(); String toString(); void maintainDatabase(); }### Answer:
@Test(expected = NullPointerException.class) public void nullPointerExceptionThrownWhenNullStringRemoveData() throws DigestException, FlashDatabaseException { rmsFastCache.removeData((String) null); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.