public static byte[] base64StringToBytes(String string) { try { return Base64.decodeBase64(string.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new NestableRuntimeException(e); } }
public static Object anyInstanceOf(Class type) { try { if (type == null || type == void.class) return null; if (type.isArray()) return anyArrayOf(type.getComponentType()); Object triangulatedInstance = tryToTriangulateFromThisClass(type); if (triangulatedInstance != null) return triangulatedInstance; if (type.isInterface()) return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {type}, new TriangulatingInvocationHandler()); if (Modifier.isAbstract(type.getModifiers())) return Enhancer.create(type, new TriangulatingInvocationHandler()); return ObjenesisHelper.newInstance(type); } catch (Exception e) { throw new NestableRuntimeException(e); } }
private static void append(final StringBuffer buffer, final Object object) { Traversal toStringTraversal = new Traversal() { public Object traverse(Object currentObject, Map referenceHistory) throws Exception { Class objectClass = object.getClass(); String className = getName(objectClass); referenceHistory.put(currentObject, className + "<circular reference>"); appendClassAndClassLoader(buffer, objectClass); appendFields(object, buffer); return buffer.toString(); } }; try { CYCLIC_REFERENCE_TRAVERSER.performWithoutFollowingCircles(toStringTraversal, object); } catch (Exception e) { throw new NestableRuntimeException(e); } }
private static void appendFields(Object object, StringBuffer buffer) { buffer.append(OPEN_BRACKET); FieldReflector reflector = new FieldReflector(object); FieldDescription[] fieldDescriptions = reflector.getAllInstanceFieldDescriptions(); for (int i = 0; i < fieldDescriptions.length; i++) { FieldDescription description = fieldDescriptions[i]; try { buffer.append(description.getFieldName()).append("="); Object fieldValue = reflector.getValue(description); if (fieldValue == null) { buffer.append("null"); } else if (fieldValue.getClass().isArray()) { appendArray(buffer, fieldValue); } else { appendValue(buffer, fieldValue, description.isPrimitive()); } buffer.append(FIELD_SEPERATOR); } catch (Exception e) { throw new NestableRuntimeException(e); } } buffer.append(CLOSE_BRACKET); }
/** * Runs the specified <code>command</code> in terminal (sh in unix/cmd in * windows) and returns the command output. * * @param command * complete command to be executed * @param envp * array of strings, each element of which has environment * variable settings in the format <i>name</i>=<i>value</i>, or * <tt>null</tt> if the subprocess should inherit the environment * of the current process. * @param workingDir * the working directory of the subprocess, or <tt>null</tt> if * the subprocess should inherit the working directory of the * current process. * @return output of the command. * @throws IOException * If an I/O error occurs * @see #runCommand(String) */ public static String runCommand(String command, String[] envp, File workingDir) throws IOException { String cmd[]; if (OS.get().isUnix()) { cmd = new String[] { "sh", "-c", command }; } else { cmd = new String[] { "cmd", "/C", command }; } Process p = Runtime.getRuntime().exec(cmd, envp, workingDir); ByteArrayOutputStream output = new ByteArrayOutputStream(); redirectStreams(p, output, System.err); try { p.waitFor(); } catch (InterruptedException ex) { throw new NestableRuntimeException("interrupted", ex); } if (p.exitValue() != 0) { throw new IOException("exitValue is " + p.exitValue()); } return output.toString(); }
private void initTables(final JdbcTemplate jdbcTemplate) { this.tables = OtterMigrateMap.makeSoftValueComputingMap(new Function<List<String>, Table>() { public Table apply(List<String> names) { Assert.isTrue(names.size() == 2); try { beforeFindTable(jdbcTemplate, names.get(0), names.get(0), names.get(1)); DdlUtilsFilter filter = getDdlUtilsFilter(jdbcTemplate, names.get(0), names.get(0), names.get(1)); Table table = DdlUtils.findTable(jdbcTemplate, names.get(0), names.get(0), names.get(1), filter); afterFindTable(table, jdbcTemplate, names.get(0), names.get(0), names.get(1)); if (table == null) { throw new NestableRuntimeException("no found table [" + names.get(0) + "." + names.get(1) + "] , pls check"); } else { return table; } } catch (Exception e) { throw new NestableRuntimeException("find table [" + names.get(0) + "." + names.get(1) + "] error", e); } } }); }
private void initShardColumns() { this.shardColumns = OtterMigrateMap.makeSoftValueComputingMap(new Function<List<String>, String>() { public String apply(List<String> names) { Assert.isTrue(names.size() == 2); try { String result = DdlUtils.getShardKeyByDRDS(jdbcTemplate, names.get(0), names.get(0), names.get(1)); if (StringUtils.isEmpty(result)) { return ""; } else { return result; } } catch (Exception e) { throw new NestableRuntimeException("find table [" + names.get(0) + "." + names.get(1) + "] error", e); } } }); }
/** * 尝试获取锁对象, 不会阻塞 * * @throws InterruptedException * @throws KeeperException */ public boolean tryLock() throws KeeperException { // 可能初始化的时候就失败了 if (exception != null) { throw exception; } if (isOwner()) {// 锁重入 return true; } acquireLock(null); if (exception != null) { unlock(); throw exception; } if (interrupt != null) { unlock(); Thread.currentThread().interrupt(); } if (other != null) { unlock(); throw new NestableRuntimeException(other); } return isOwner(); }
public static String bytesToString(byte[] bytes) { try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new NestableRuntimeException(e); } }
public static byte[] stringToBytes(String string) { try { return string.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new NestableRuntimeException(e); } }
public static String bytesToBase64String(byte[] bytes) { try { return new String(Base64.encodeBase64(bytes), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new NestableRuntimeException(e); } }
/** * */ public static Map<String, Object> inspect(Entity entity) { // Precondition checking if(entity == null) { throw new IllegalArgumentException("invalid parameter entity"); } final Class<?> clazz = entity.getClass(); try { List<ColumnField> columnFields = COLUMN_FIELD_CACHE.get(clazz); if(columnFields == null) { // columnFields = new ArrayList<>(); List<Field> fields = Fields.getAllFields(clazz, true); for(Field field : fields) { columnFields.addAll(getColumnFields(field)); } List<ColumnField> existing = COLUMN_FIELD_CACHE.putIfAbsent(clazz, columnFields); if(existing != null) { columnFields = existing; } } Map<String, Object> r = new HashMap<>(); for(ColumnField cf : columnFields) { r.put(cf.getColumn(), cf.getFieldValue(entity)); } return r; } catch(Exception e) { throw new NestableRuntimeException("failed to inspect class: " + clazz, e); } }
@Override public void sendError(final int sc) { status = sc; operations.add(new ResponseOperation() { @Override public void apply() { try { wrapped.sendError(sc); } catch (final IOException e) { throw new NestableRuntimeException(e); } } }); }
@Override public void sendError(final int sc, final String msg) throws IOException { status = sc; operations.add(new ResponseOperation() { @Override public void apply() { try { wrapped.sendError(sc, msg); } catch (final IOException e) { throw new NestableRuntimeException(e); } } }); }
@Override public void sendRedirect(final String location) throws IOException { operations.add(new ResponseOperation() { @Override public void apply() { try { wrapped.sendRedirect(location); } catch (final IOException e) { throw new NestableRuntimeException(e); } } }); }
@Override public BO clone() { try { logger.debug("cloning this " + this.toString()); return (BO) super.clone(); } catch (final CloneNotSupportedException e) { logger.error(e); throw new NestableRuntimeException(e); } }
public static Class[] getAllProductionClasses(Class exampleProductionClass, String nonProductionRootPackageName) { try { File rootDirectory = getRootDirectoryOf(exampleProductionClass); List classes = new ArrayList(); Collection classFiles = FileUtils.listFiles(rootDirectory, new String[] {"class"}, true); for (Iterator iterator = classFiles.iterator(); iterator.hasNext();) { File classFile = (File) iterator.next(); String className = getClassName(rootDirectory, classFile); if (!className.startsWith(nonProductionRootPackageName)) classes.add(ClassUtils.getClass(className)); } return (Class[]) classes.toArray(new Class[classes.size()]); } catch (Exception e) { throw new NestableRuntimeException(e); } }
@SuppressWarnings({ "unchecked" }) public R getResult() throws E { if (exceptionClass.isInstance(ex)) { throw (E) ex; } else if (ex != null) { throw new NestableRuntimeException(ex); } return r; }
public static String toSystemID(URL url) { try { if ("file".equals(url.getProtocol())) { return new File(url.toURI()).getAbsolutePath(); } else { return url.toString(); } } catch (URISyntaxException ex) { throw new NestableRuntimeException(ex); } }
public static String fileToString(final String fileName) { try { return FileCopyUtils.copyToString(new InputStreamReader(new ClassPathResource(fileName).getInputStream())); } catch (IOException e) { throw new NestableRuntimeException(e); } }
@Override public synchronized boolean addRow(String[] row) { if (row.length > this.columns.length) { throw new IllegalArgumentException(String.format("Invalid number of result columns: got %s, expected %s",row.length, this.columns.length)); } if (row.length < this.columns.length) { LogFactory.getLog(SearchResultCollector.class).warn(String.format("Row %s: Invalid number of result columns: got %s, expected ",this.count, row.length, this.columns.length)); } if (state() > BUFFER_FULL) { if (this.exception == null) setException(new RetsException("Attempting to add rows to buffer when in complete state")); throw new NestableRuntimeException(this.exception); } // check complete. while (checkRuntime() && state() == BUFFER_FULL) { _wait(); if (state() >= BUFFER_FULL) { if (this.exception == null) setException(new RetsException("Timeout writing to streaming result set buffer, timeout length = " + this.timeout)); throw new NestableRuntimeException(this.exception); } } this.buffer.addLast(row); if (this.bufferSize == this.buffer.size()) pushState(BUFFER_FULL); else pushState(BUFFER_AVAILABLE); this.notifyAll(); return true; }
private synchronized boolean checkRuntime() { try { return checkException(); } catch (RetsException e) { throw new NestableRuntimeException(e); } }
private void _wait() { try { wait(this.timeout); } catch (InterruptedException e) { pushState(COMPLETE); throw new NestableRuntimeException(e); } }
public static String urlEncode(String string) { try { return new URLCodec().encode(string); } catch (EncoderException e) { throw new NestableRuntimeException(e); } }
public static String urlDecode(String string) { try { return new URLCodec().decode(string); } catch (DecoderException e) { throw new NestableRuntimeException(e); } }
/** * 尝试获取锁操作,阻塞式可被中断 */ public void lock() throws InterruptedException, KeeperException { // 可能初始化的时候就失败了 if (exception != null) { throw exception; } if (interrupt != null) { throw interrupt; } if (other != null) { throw new NestableRuntimeException(other); } if (isOwner()) {// 锁重入 return; } BooleanMutex mutex = new BooleanMutex(); acquireLock(mutex); mutex.get(); // 避免zookeeper重启后导致watcher丢失,会出现死锁使用了超时进行重试 // try { // mutex.get(DEFAULT_TIMEOUT_PERIOD, TimeUnit.MILLISECONDS);// 阻塞等待值为true // } catch (TimeoutException e) { // if (!mutex.state()) { // lock(); // } // } if (exception != null) { unlock(); throw exception; } if (interrupt != null) { unlock(); throw interrupt; } if (other != null) { unlock(); throw new NestableRuntimeException(other); } }
/** * 替换text中的占位符<br/> * eg:<br/> * 1.text值为:<br/> * ${hi},我是${user.name},英文名是${user.eglish.name}!<br/><br/> * 2.values值为:<br/> * <code> * Map<String, String> params = new HashMap<String, String>();<br/> * params.put("user.name", "孙昊");<br/> * params.put("user.eglish.name", "Hello World");<br/> * params.put("hi", "你好");<br/><br/> * </code> * 那么结果将是:<br/> * 你好,我是孙昊,英文名是Hello World! * * @param text 要替换的文本(包含${...}) * @param placeholderAsDefaultValue 如果一个占位符找不到值,是否使用占位符作为值 * @param values 值的map集合 * @return */ public static String replacePlaceholder(String text, boolean placeholderAsDefaultValue, Map<String, String> values) { Assert.hasText(text, "source text can't be null!"); if (!needReplace(text)) { return text; } Assert.notEmpty(values, "values can't be null!"); //1.根据前缀分组 String[] groups = StringUtils.split(text, PLACEHOLDER_PREFIX); //2.遍历分组,如果有后缀,则取出 int length = groups.length; //占位符在第一位 boolean placeholderInFirst = StringUtils.startsWith(text, PLACEHOLDER_PREFIX); Assert.isTrue(placeholderInFirst || length > 1, "given text has no placeholder!"); List<String> placeholders = new ArrayList<>(); int start = placeholderInFirst ? 0 : 1; for (int i = start; i < length; i++) { if (i < length) { String t = groups[i]; //3.将所有的占位符取出 if (StringUtils.contains(t, PLACEHOLDER_SUFFIX)) { placeholders.add(StringUtils.substring(t, 0, StringUtils.indexOf(t, PLACEHOLDER_SUFFIX))); } } } //4.进行替换 String result = text; for (String ph : placeholders) { String placeholder = PLACEHOLDER_PREFIX + ph + PLACEHOLDER_SUFFIX; String value = values.get(ph); if (StringUtils.isEmpty(value) && !placeholderAsDefaultValue) { throw new NestableRuntimeException("process text '{" + text + "}' error! placeholder is '{" + placeholder + "}'!"); } value = (StringUtils.isNotEmpty(value) ? value : ph); //5.替换text result = StringUtils.replace(result, placeholder, value); } return result; }