/** * 根据传递的对象提供对象的json格式,格式如下: {"user":{"id":"11","email":"*****@*****.**","name":"名字" * ,"enable":"","roleCode":"","password":"","userType":""}} * * @param obj * @return * @throws JSONException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static String getJsonObject(Object obj) throws JSONException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { String json = "{}"; JSONObject jsonObject = new JSONObject(json); if (ObjectUtils.isNotEmpty(obj)) { Class clz = obj.getClass(); String className = StringHelper.getStrFirstLower(clz.getSimpleName()); Map<String, String> property = new HashMap<String, String>(); Class[] paraTypes = new Class[] {String.class}; Method[] methods = clz.getDeclaredMethods(); for (Method method : methods) { String methodName = method.getName(); if (methodName.startsWith("get")) { property.put( StringHelper.getStrFirstLower(method.getName().replace("get", "")), String.valueOf(method.invoke(obj, null))); } } jsonObject.put(className, property); } String result = jsonObject.toString().replace("null", ""); return result; }
public static final File writeFileItemToFolder( FileItem fileItem, File folder, boolean overwrite, boolean rename) throws IOException { if (!folder.isDirectory()) { return null; } File file = new File( URLHelper.mergePath( folder.getAbsolutePath(), StringHelper.createFileName(StringHelper.getFileNameFromPath(fileItem.getName())))); if (!file.exists()) { file.createNewFile(); } else { if (!overwrite && !rename) { throw new FileExistsException("File already exists."); } if (rename) { file = ResourceHelper.getFreeFileName(file); } } InputStream in = null; try { in = fileItem.getInputStream(); writeStreamToFile(in, file); return file; } catch (IOException e) { ResourceHelper.closeResource(in); file.delete(); throw e; } finally { ResourceHelper.closeResource(in); } }
public String getDBUnitTestData(String columnName, String javaType, int size) { if (size <= 0) size = 2; int MAX_SIZE = 3; if (javaType.indexOf("Boolean") >= 0) { return "0"; } if (javaType.indexOf("Timestamp") >= 0) { return new Timestamp(System.currentTimeMillis()).toString(); } if (javaType.indexOf("java.sql.Date") >= 0) { return new java.sql.Date(System.currentTimeMillis()).toString(); } if (javaType.indexOf("java.sql.Time") >= 0) { return new java.sql.Time(System.currentTimeMillis()).toString(); } if (javaType.indexOf("java.util.Date") >= 0) { return new Timestamp(System.currentTimeMillis()).toString(); } if (javaType.indexOf("String") >= 0) { if (size > columnName.length()) { int tempSize = Math.min(size - columnName.length(), MAX_SIZE); return columnName + StringHelper.randomNumeric(tempSize); } return StringHelper.randomNumeric(Math.min(size, MAX_SIZE)); } if (isNumberType(javaType)) { return StringHelper.randomNumeric(Math.min(size, MAX_SIZE)); } return ""; }
/** * Constructs this object from the raw data. Used when reading in a format record * * @param t the raw data * @param ws the workbook settings */ public FontRecord(Record t, WorkbookSettings ws) { super(t); byte[] data = getRecord().getData(); pointHeight = IntegerHelper.getInt(data[0], data[1]) / EXCEL_UNITS_PER_POINT; colourIndex = IntegerHelper.getInt(data[4], data[5]); boldWeight = IntegerHelper.getInt(data[6], data[7]); scriptStyle = IntegerHelper.getInt(data[8], data[9]); underlineStyle = data[10]; fontFamily = data[11]; characterSet = data[12]; initialized = false; if ((data[2] & 0x02) != 0) { italic = true; } if ((data[2] & 0x08) != 0) { struckout = true; } int numChars = data[14]; if (data[15] == 0) { name = StringHelper.getString(data, numChars, 16, ws); } else if (data[15] == 1) { name = StringHelper.getUnicodeString(data, numChars, 16); } else { // Some font names don't have the unicode indicator name = StringHelper.getString(data, numChars, 15, ws); } }
/** * 根据传递列表值返回列表格式json数据,格式如下 {"userList":[{"id":"111","email":"[email protected]","name" * :"名字1","enable":"","roleCode" :"","password":"","userType":""},{"id":"111", * "email":"[email protected]","name" :"名字1","enable":"","roleCode":"","password":"" * ,"userType":""},{"id":"111", "email":"[email protected]","name":"名字1","enable":"" * ,"roleCode":"","password":"" ,"userType":""},{"id":"111","email":"[email protected]" * ,"name":"名字1","enable":"" ,"roleCode":"","password":"","userType":""},{"id" * :"111","email":"[email protected]" ,"name":"名字1","enable":"","roleCode":"","password" * :"","userType":""},{"id" :"111","email":"[email protected]","name":"名字1","enable" * :"","roleCode":"","password" :"","userType":""},{"id":"111","email":"[email protected]" * ,"name":"名字1","enable" :"","roleCode":"","password":"","userType":""},{"id" * :"111","email":"[email protected]" ,"name":"名字1","enable":"","roleCode":"","password" * :"","userType":""},{"id" :"111","email":"[email protected]","name":"名字1","enable" * :"","roleCode":"","password" :"","userType":""},{"id":"111","email":"[email protected]" * ,"name":"名字1","enable" :"","roleCode":"","password":"","userType":""},{"id" * :"111","email":"[email protected]" ,"name":"名字1","enable":"","roleCode":"","password" * :"","userType":""},{"id" :"111","email":"[email protected]","name":"名字1","enable" * :"","roleCode":"","password" :"","userType":""},{"id":"111","email":"[email protected]" * ,"name":"名字1","enable" :"","roleCode":"","password":"","userType":""},{"id" * :"111","email":"[email protected]" * ,"name":"名字1","enable":"","roleCode":"","password":"","userType":""}]} * * @param objs * @param clz * @return * @throws JSONException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static String getJsonObject(List objs) throws JSONException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { String json = "{}"; JSONObject jsonObject = new JSONObject(json); String className = null; if (ObjectUtils.isNotEmpty(objs)) { List propertyList = new ArrayList(); Map<String, String> property = new HashMap<String, String>(); for (Object obj : objs) { className = StringHelper.getStrFirstLower(obj.getClass().getSimpleName()); Class[] paraTypes = new Class[] {String.class}; Method[] methods = obj.getClass().getDeclaredMethods(); // 过滤非java自由对象以及项目对象外的对象 String methodValues = ""; for (Method method : methods) { String methodName = method.getName(); if (methodName.startsWith("get")) { property.put( StringHelper.getStrFirstLower(method.getName().replace("get", "")), String.valueOf(method.invoke(obj, null))); propertyList.add(property); } } } jsonObject.put(className + "List", propertyList); } String result = jsonObject.toString().replace("null", ""); return result; }
public static IIOMetadata getImageMetadata(File image) throws IOException { Iterator readers = ImageIO.getImageReadersBySuffix(StringHelper.getFileExtension(image.getName())); if (StringHelper.isImage(image.getName())) { if (!readers.hasNext()) { return null; } else { ImageReader imageReader = (ImageReader) readers.next(); FileImageInputStream in = new FileImageInputStream(image); try { imageReader.setInput(in); return imageReader.getImageMetadata(0); } finally { if (in != null) { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } } } } else { return null; } }
public static String veryShortMessage(final Throwable t) { String msg = t.getMessage(); if (!StringHelper.isEmpty(msg)) return msg; msg = t.getClass().getSimpleName(); if (!StringHelper.isEmpty(msg)) return msg; return String.valueOf(t); }
@Test public void join() { assertEquals("foo,bar,baz", StringHelper.join(",", new String[] {"foo", "bar", "baz"})); assertEquals("foobarbaz", StringHelper.join(null, new String[] {"foo", "bar", "baz"})); // TODO: is this the intended behavior? assertEquals("foo,,bar", StringHelper.join(",", new String[] {"foo", null, "bar"})); assertNull(StringHelper.join(null, null)); }
public String getCompileClassPath() { String compileClassPath = StringHelper.removeQuotesOS("\".") + File.pathSeparator + Oncotcap.getInstallDir() + "bin" + File.pathSeparator + Oncotcap.getProgramDir() + File.pathSeparator + Oncotcap.getInstallDir() + "lib" + File.separator + "tools.jar" + File.pathSeparator + Oncotcap.getInstallDir() + "lib" + File.separator + "protege.jar" + File.pathSeparator + FileHelper.sansTrailingSeparator(Oncotcap.getTempPath()); // packageBaseName; String xtraPath = Oncotcap.getExtraCompilerClassPath().trim(); if (xtraPath != null && !xtraPath.equals("")) { if (!xtraPath.startsWith(File.pathSeparator)) compileClassPath = compileClassPath + File.pathSeparator; compileClassPath = compileClassPath + xtraPath; } String strPluginDir = Oncotcap.getInstallDir() + "plugins"; if (FileHelper.fileExists(strPluginDir)) { strPluginDir = strPluginDir + File.separator; File pluginDir = new File(strPluginDir); { if (pluginDir.isDirectory()) { File[] jars = pluginDir.listFiles(); if (jars != null) { for (int n = 0; n < jars.length; n++) { if (jars[n].getName().endsWith(".jar")) compileClassPath = compileClassPath + File.pathSeparator + strPluginDir + jars[n].getName(); } } } } } compileClassPath = compileClassPath + StringHelper.removeQuotesOS("\""); return (compileClassPath); }
public void render(StringBuffer buffer, String alias, Map enabledFilters) { if (filterNames != null && filterNames.length > 0) { for (int i = 0, max = filterNames.length; i < max; i++) { if (enabledFilters.containsKey(filterNames[i])) { final String condition = filterConditions[i]; if (StringHelper.isNotEmpty(condition)) { buffer .append(" and ") .append(StringHelper.replace(condition, FilterImpl.MARKER, alias)); } } } } }
@Override public void ExecuteCommand(UICommand command) { super.ExecuteCommand(command); if (StringHelper.stringsEqual(command.getName(), "AddHost")) { AddHost(); } if (StringHelper.stringsEqual(command.getName(), "OnConfirmPMHost")) { OnConfirmPMHost(); } if (StringHelper.stringsEqual(command.getName(), "OnAddHost")) { OnAddHost(); } if (StringHelper.stringsEqual(command.getName(), "SelectHost")) { SelectHost(); } if (StringHelper.stringsEqual(command.getName(), "OnSelectHost")) { OnSelectHost(); } if (StringHelper.stringsEqual(command.getName(), "Cancel")) { Cancel(); } if (StringHelper.stringsEqual(command.getName(), "CancelConfirm")) { CancelConfirm(); } if (StringHelper.stringsEqual(command.getName(), "CancelConfirmWithFocus")) { CancelConfirmWithFocus(); } }
private Table _getTable(String catalog, String schema, String tableName) throws SQLException { if (tableName == null || tableName.trim().length() == 0) throw new IllegalArgumentException("tableName must be not empty"); catalog = StringHelper.defaultIfEmpty(catalog, null); schema = StringHelper.defaultIfEmpty(schema, null); Connection conn = getConnection(); DatabaseMetaData dbMetaData = conn.getMetaData(); ResultSet rs = dbMetaData.getTables(catalog, schema, tableName, null); while (rs.next()) { Table table = createTable(conn, rs); return table; } return null; }
public static void fixNamespaceForXsiType(XmlObject content, Map<?, ?> namespaces) { final XmlCursor cursor = content.newCursor(); while (cursor.hasNextToken()) { if (cursor.toNextToken().isStart()) { final String xsiType = cursor.getAttributeText(W3CConstants.QN_XSI_TYPE); if (xsiType != null) { final String[] toks = xsiType.split(":"); if (toks.length > 1) { String prefix = toks[0]; String localName = toks[1]; String namespace = (String) namespaces.get(prefix); if (Strings.isNullOrEmpty(namespace)) { namespace = CodingRepository.getInstance().getNamespaceFor(prefix); } if (StringHelper.isNotEmpty(namespace)) { cursor.setAttributeText( W3CConstants.QN_XSI_TYPE, Joiner.on(Constants.COLON_CHAR) .join( XmlHelper.getPrefixForNamespace(content, (String) namespaces.get(prefix)), localName)); } } } } } cursor.dispose(); }
/** * @param target * @param data * @param encoding */ public static void save(File target, String data, String encoding) { try { save(new FileOutputStream(target), data, StringHelper.check4xMacRoman(encoding)); } catch (IOException e) { throw new OLATRuntimeException(FileUtils.class, "could not save file", e); } }
/** * Check if namespace is not null and equals GML 3.1.1 or GML 3.2.1 namespace. * * @param namespaceToCheck Namespace to check * @param namespaces GML namespaces * @return <code>true</code>, if namespaceToCheck is a GML namespace */ private static boolean isNotNullAndEqualsNSs( String namespaceToCheck, Collection<String> namespaces) { if (StringHelper.isNotEmpty(namespaceToCheck)) { return namespaces.contains(namespaceToCheck); } return false; }
/* * Sample url * http://maps.googleapis.com/maps/api/directions/json?origin=pune * &destination=amravati&sensor=false&mode=driving * * result{ "routes" : [{ "bounds" : { "northeast" : { "lat" : 20.92891 "lng" * : 77.764730 }, "southwest" : { "lat" : 18.520650,"lng" : 73.856740 } * "copyrights" : "Map data ©2013 Google", "legs" : [ { "distance" : { * "text" : "603 km", "value" : 602864 }, "duration" : { "text" : * "10 hours 1 min", "value" : 36060 }, "end_address" : * "Amravati, Maharashtra, India", "end_location" : { "lat" : 20.925830, * "lng" : 77.764730 }, "start_address" : "Pune, Maharashtra, India", * "start_location" : { "lat" : 18.520650, "lng" : 73.856740 }, */ public static String getlocationCity(double lat, double lonng) { String location = ""; JSONArray ja; String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lonng + "&sensor=true"; StringBuffer json = StringHelper.readURLContent(url); try { System.out.println("URL " + url); JSONObject myjson = new JSONObject(json.toString()); ja = (JSONArray) myjson.get("results"); JSONArray add = (JSONArray) ((JSONObject) ja.get(0)).get("address_components"); JSONObject city = (JSONObject) add.get(4); location = city.getString("long_name"); System.out.println("......................................" + location); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return location; }
public static String getFileContent(File file) throws FileNotFoundException, IOException { String ext = FilenameUtils.getExtension(file.getName()); String outContent = ""; try { if (ext.toLowerCase().equals("doc")) { if (file != null) { WordExtractor we = new WordExtractor(new FileInputStream(file)); outContent = we.getText(); } else { logger.warning("file not found : " + file); } } else if (ext.toLowerCase().equals("pdf")) { PDDocument doc = PDDocument.load(file); PDFTextStripper text = new PDFTextStripper(); outContent = text.getText(doc); doc.close(); } else if (StringHelper.isHTML(file.getName())) { return loadStringFromFile(file); } } catch (Throwable t) { logger.warning("error when read : " + file + "+ [" + t.getMessage() + "]"); t.printStackTrace(); } return outContent; }
private String AvailableName(java.util.ArrayList<String> list) { String retVal = getCommonName(); java.util.ArrayList<Integer> notAvialbleNumberList = new java.util.ArrayList<Integer>(); String temp; for (String str : list) { temp = str.replace(getCommonName(), ""); if (StringHelper.isNullOrEmpty(temp)) { temp = "0"; } int tempInt = 0; RefObject<Integer> tempRef_tempInt = new RefObject<Integer>(tempInt); boolean tempVar = IntegerCompat.TryParse(temp, tempRef_tempInt); tempInt = tempRef_tempInt.argvalue; if (tempVar) { notAvialbleNumberList.add(tempInt); } } Collections.sort(notAvialbleNumberList); int i = 0; for (i = 0; i < notAvialbleNumberList.size(); i++) { if (notAvialbleNumberList.get(i) == i) { continue; } break; } if (i > 0) { retVal = getCommonName() + (new Integer(i)).toString(); } return retVal; }
/** * Stores value of previously defined XML node * * @param text - value of node */ public void setValue(String text) { readyForNewLine = false; tagIsEmpty = false; finishTag(); if (lastTagHadAttributes) { writer.write( LF + WikiTableDriver.DELIM + WikiTableDriver.QUOTES + WikiTableDriver.SET_VALUE + WikiTableDriver.QUOTES + WikiTableDriver.DELIM); quickNodeValue = false; } else { String startTag = StringHelper.replace( writer.substring(startPointer), WikiTableDriver.START_NODE, WikiTableDriver.SET_NODE_VALUE); if (this.useLineSeparateBetweenTags) { writer.write(LF + WikiTableDriver.DELIM); } writer.setPointer(startPointer); writer.write(startTag); quickNodeValue = true; } writeText(writer, text); writer.write(WikiTableDriver.DELIM); }
public void set_IsBuyForCombo(String value) { if (StringHelper.isNullOrEmpty(value)) { value = this._isBuyForCurrent ? Language.Buy : Language.Sell; } this._isBuyForCombo = value; this.setIsBuyForCurrent(value.equalsIgnoreCase(Language.Buy)); }
/** * Parse XML document from HTTP-Post request. * * @param request HTTP-Post request * @return XML document * @throws OwsExceptionReport If an error occurs */ public static XmlObject parseXmlSosRequest(final HttpServletRequest request) throws OwsExceptionReport { XmlObject doc; try { if (request.getParameterMap().isEmpty()) { final String requestContent = StringHelper.convertStreamToString( HTTPUtils.getInputStream(request), request.getCharacterEncoding()); doc = parseXmlString(requestContent); } else { doc = XmlObject.Factory.parse( SosHelper.parseHttpPostBodyWithParameter( request.getParameterNames(), request.getParameterMap())); } } catch (final XmlException xmle) { throw new NoApplicableCodeException() .causedBy(xmle) .withMessage( "An xml error occured when parsing the request! Message: %s", xmle.getMessage()); } catch (final IOException ioe) { throw new NoApplicableCodeException() .causedBy(ioe) .withMessage("Error while reading request! Message: %s", ioe.getMessage()); } // validateDocument(doc); return doc; }
public static String translate(String key, Locale preferredLocale, Object... msg) { if (instance == null) createInstance(); return StringHelper.parseColors( msg.length == 0 ? instance.translate(key, preferredLocale) : instance.format(key, preferredLocale, msg)); }
/** * return a free file name. if file exist add a number as suffix. * * @param file * @return */ public static synchronized File getFreeFileName(File file) { if (!file.exists()) { return file; } File folder = file.getParentFile(); String newName = file.getName(); String ext = StringHelper.getFileExtension(file.getName()); String fileName = StringHelper.getFileNameWithoutExtension(file.getName()); for (int i = 1; i < 999999; i++) { newName = fileName + "_" + i + '.' + ext; File newFile = new File(URLHelper.mergePath(folder.getAbsolutePath(), newName)); if (!newFile.exists()) { return newFile; } } return null; }
/** * 解析attributes为hashMap * * @param attributes 格式: name='badqiu' sex='F' * @return */ public static Map<String, String> parse2Attributes(String attributes) { Map result = new HashMap(); Pattern p = Pattern.compile("(\\w+?)=['\"](.*?)['\"]"); Matcher m = p.matcher(attributes); while (m.find()) { result.put(m.group(1), StringHelper.unescapeXml(m.group(2))); } return result; }
public static Boolean Login(String userName, String password) { if (StringHelper.IsNullOrWhitespace(userName) || StringHelper.IsNullOrWhitespace(password)) return false; userName = userName.toLowerCase(); String passwordHash = DigestUtils.md5Hex(password); UserEntity user = UserEntityHelper.GetUserByUserName(userName); if (user == null) return false; if (!user.getPassword().equals(passwordHash)) return false; if (user.getIsEnabled() == false) return false; SessionManager.getInstance().createSession(user); return true; }
public static InputStream getInputStream(String data, String encoding) { try { byte[] ba = data.getBytes(StringHelper.check4xMacRoman(encoding)); ByteArrayInputStream bis = new ByteArrayInputStream(ba); return bis; } catch (IOException e) { throw new OLATRuntimeException(FileUtils.class, "could not save to output stream", e); } }
@Override public void ExecuteCommand(UICommand command) { super.ExecuteCommand(command); if (command == getNewCommand()) { New(); } else if (command == getEditCommand()) { Edit(); } else if (command == getRemoveCommand()) { remove(); } else if (StringHelper.stringsEqual(command.getName(), "OnSave")) { OnSave(); } else if (StringHelper.stringsEqual(command.getName(), "Cancel")) { Cancel(); } else if (StringHelper.stringsEqual(command.getName(), "OnRemove")) { OnRemove(); } }
/** * @param target * @param data * @param encoding */ public static void save(OutputStream target, String data, String encoding) { try { byte[] ba = data.getBytes(StringHelper.check4xMacRoman(encoding)); ByteArrayInputStream bis = new ByteArrayInputStream(ba); bcopy(bis, target, "saveDataToFile"); } catch (IOException e) { throw new OLATRuntimeException(FileUtils.class, "could not save to output stream", e); } }
@Override public void ExecuteCommand(UICommand command) { super.ExecuteCommand(command); if (command == getManageCommand()) { Manage(); } else if (command == getSetAsDisplayCommand()) { SetAsDisplay(); } else if (StringHelper.stringsEqual(command.getName(), "OnManage")) { OnManage(); } else if (StringHelper.stringsEqual(command.getName(), "New")) { New(); } else if (StringHelper.stringsEqual(command.getName(), "OnSave")) { OnSave(); } else if (StringHelper.stringsEqual(command.getName(), "Cancel")) { Cancel(); } }
public void testAcquireToken_KeyCred() throws Exception { ctx = PowerMock.createPartialMock( AuthenticationContext.class, new String[] {"acquireTokenCommon"}, TestConfiguration.AAD_TENANT_ENDPOINT, true, service); PowerMock.expectPrivate( ctx, "acquireTokenCommon", EasyMock.isA(AdalAuthorizatonGrant.class), EasyMock.isA(ClientAuthentication.class), EasyMock.isA(ClientDataHttpHeaders.class)) .andReturn( new AuthenticationResult( "bearer", "accessToken", null, new Date().getTime(), null, null, false)); final KeyStore keystore = KeyStore.getInstance("PKCS12", "SunJSSE"); keystore.load( new FileInputStream( this.getClass().getResource(TestConfiguration.AAD_CERTIFICATE_PATH).getFile()), TestConfiguration.AAD_CERTIFICATE_PASSWORD.toCharArray()); final String alias = keystore.aliases().nextElement(); final PrivateKey key = (PrivateKey) keystore.getKey(alias, TestConfiguration.AAD_CERTIFICATE_PASSWORD.toCharArray()); final X509Certificate cert = (X509Certificate) keystore.getCertificate(alias); PowerMock.replay(ctx); final Future<AuthenticationResult> result = ctx.acquireToken( TestConfiguration.AAD_RESOURCE_ID, AsymmetricKeyCredential.create(TestConfiguration.AAD_CLIENT_ID, key, cert), null); final AuthenticationResult ar = result.get(); assertNotNull(ar); assertFalse(StringHelper.isBlank(result.get().getAccessToken())); assertTrue(StringHelper.isBlank(result.get().getRefreshToken())); PowerMock.verifyAll(); PowerMock.resetAll(ctx); }