Java Code Examples for jodd.io.FileUtil

The following examples show how to use jodd.io.FileUtil. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public void delete(File file) throws IOException {
    String fileName = file.getName();
    if(file.isDirectory()&&(fileName.equals(".settings")
            || fileName.equals("target"))){
        FileUtil.delete(file);
        System.out.println("删除文件夹"+file.getAbsolutePath()+fileName);
    }else if(file.isFile() && (fileName.equals(".classpath")
            || fileName.equals(".project") || fileName.equals(".gitignore"))
    ){
        file.delete();
        System.out.println("删除文件"+file.getAbsolutePath()+fileName);
    }
    File[] files = file.listFiles();
    if(files == null){
        return;
    }
    for (int i = 0; i < files.length; i++) {
        File f = files[i];
        this.delete(f);
    }
}
 
Example 2
Source Project: DAFramework   Source File: SysToolkit.java    License: MIT License 6 votes vote down vote up
public static void mklink(String target, String source) throws Exception {
	File fTarget = new File(polishFilePath(target));
	if (fTarget.exists() && fTarget.isDirectory()) {
		if (isSymbolicLink(target)) {
			exec("rd /q " + fTarget.getAbsolutePath(), ".", true, true);
		} else {
			FileUtil.deleteDir(fTarget);
		}
	}
	if (!fTarget.getParentFile().exists()) {
		FileUtil.mkdirs(fTarget.getParentFile());
	}
	File fSource = new File(polishFilePath(source));
	if (fSource.isDirectory()) {
		exec("mklink /d " + target + " " + source, ".", true, true);
	} else {
		exec("mklink /h " + target + " " + source, ".", true, true);
	}
}
 
Example 3
Source Project: wES   Source File: SysToolkit.java    License: MIT License 6 votes vote down vote up
public static void mklink(String target, String source) throws Exception {
	File fTarget = new File(polishFilePath(target));
	if (fTarget.exists() && fTarget.isDirectory()) {
		if (isSymbolicLink(target)) {
			exec("rd /q " + fTarget.getAbsolutePath(), ".", true, true);
		} else {
			FileUtil.deleteDir(fTarget);
		}
	}
	if (!fTarget.getParentFile().exists()) {
		FileUtil.mkdirs(fTarget.getParentFile());
	}
	File fSource = new File(polishFilePath(source));
	if (fSource.isDirectory()) {
		exec("mklink /d " + target + " " + source, ".", true, true);
	} else {
		exec("mklink /h " + target + " " + source, ".", true, true);
	}
}
 
Example 4
Source Project: wES   Source File: EsRestSpecGen.java    License: MIT License 6 votes vote down vote up
public void writeJavaFile() {
	try {
		String pkg2 = pkg + ".actions";
		StringBuilder javaCodes = new StringBuilder();
		javaCodes.append("package " + pkg2 + ";\n\n");

		javaCodes.append("import okhttp3.HttpUrl;\n" +
				"import org.datasays.wes.core.RequestInfo;\n" +
				"import org.datasays.wes.types.*;\n");
		javaCodes.append(codes.toString());
		javaCodes.append("}\n");
		String filePath = sourceDir + pkg2.replace('.', File.separatorChar) + File.separatorChar;
		FileUtil.mkdirs(filePath);
		FileUtil.writeString(filePath + clsName + ".java", javaCodes.toString(), "utf-8");
		codes = new StringBuilder();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 5
Source Project: wES   Source File: EsRestSpecGen.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
	EsRestSpecGen codeGen = new EsRestSpecGen();
	String specHome = ".\\api\\";
	codeGen.sourceDir = "..\\wES-client\\src\\main\\java\\";
	codeGen.pkg = "org.datasays.wes";
	Iterator<File> iterator = FindFileUtil.search(true, false, specHome);
	while (iterator.hasNext()) {
		File f = iterator.next();
		if (f.getName().endsWith(".json")) {
			try {
				String jsoncode = FileUtil.readUTFString(f);
				codeGen.parseCode(jsoncode);
				codeGen.writeJavaFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	codeGen.writeEsHelper();
}
 
Example 6
Source Project: wES   Source File: EsRestSpecGen4Retrofit.java    License: MIT License 6 votes vote down vote up
public void writeToFile(String file) {
	StringBuilder javaCodes = new StringBuilder();
	javaCodes.append("package org.datasays.wes.client;\n\n");

	javaCodes.append("import retrofit2.Call;\n");
	javaCodes.append("import retrofit2.http.Body;\n");
	javaCodes.append("import retrofit2.http.DELETE;\n");
	javaCodes.append("import retrofit2.http.GET;\n");
	javaCodes.append("import retrofit2.http.HEAD;\n");
	javaCodes.append("import retrofit2.http.POST;\n");
	javaCodes.append("import retrofit2.http.PUT;\n");
	javaCodes.append("import retrofit2.http.Path;\n\n");

	javaCodes.append("public interface EsService {\n");
	javaCodes.append("	" + codes.toString() + "\n");

	javaCodes.append("}\n");
	try {
		FileUtil.writeString(file, javaCodes.toString(), "utf-8");
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 7
Source Project: wES   Source File: EsRestSpecGen4Retrofit.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
	EsRestSpecGen4Retrofit parser = new EsRestSpecGen4Retrofit();
	String specHome = ".\\wES-toolkit\\api\\";
	Iterator<File> iterator = FindFileUtil.search(true, false, specHome);
	while (iterator.hasNext()) {
		File f = iterator.next();
		if (f.getName().endsWith(".json")) {
			try {
				String jsoncode = FileUtil.readUTFString(f);
				parser.parseCode(jsoncode);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	parser.writeToFile(".\\wES-client\\src\\main\\java\\org\\datasays\\wes\\client\\EsService.java");
}
 
Example 8
Source Project: GitToolBox   Source File: GitTestExtension.java    License: Apache License 2.0 6 votes vote down vote up
private void prepareImpl(GitTestSetup setup) throws Exception {
  Path rootPath = setup.getRootPath();
  File rootDir = rootPath.toFile();
  if (FileUtil.isExistingFolder(rootDir)) {
    log.info("Deleting existing git root dir {}", rootPath);
    FileUtil.deleteDir(rootDir);
  }
  log.info("Initializing git [bare={}] repository in {}", setup.isBare(), rootPath);
  try (Git git = Git.init().setDirectory(rootDir).setBare(setup.isBare()).call()) {
    if (!setup.isBare()) {
      StoredConfig config = git.getRepository().getConfig();
      config.load();
      config.setString("user", null, "name", "Jon Snow");
      config.setString("user", null, "email", "[email protected]");
      config.save();
    }
    log.info("Setup initial git repository state in {}", rootPath);
    setup.setup(git);
    git.close();
    log.info("Git repository ready in {}", rootPath);
  }
}
 
Example 9
Source Project: DAFramework   Source File: VcfUtils.java    License: MIT License 5 votes vote down vote up
public static void exportVcf(List<VcfBean> beans, File vcfFile) {
	try {
		StringBuffer sb = new StringBuffer();
		for (VcfBean bean : beans) {
			sb.append("BEGIN:VCARD\r\n");
			sb.append("VERSION:3.0\r\n");
			sb.append("N;CHARSET=UTF-8:;‭‬‭‬‭" + bean.getFullName() + ";;;\r\n");
			sb.append("FN;CHARSET=UTF-8: ‭‬‭‬‭" + bean.getFullName() + "\r\n");
			if ("" != bean.getOrg() && bean.getOrg() != null) {
				sb.append("ORG:" + bean.getOrg() + "\r\n");
			}
			if ("" != bean.getTitle() && bean.getTitle() != null) {
				sb.append("TITLE:" + bean.getTitle() + "\r\n");
			}
			if ("" != bean.getAddress() && bean.getAddress() != null) {
				sb.append("ADR;HOME:;;;" + bean.getAddress() + ";;;\r\n");
			}
			if ("" != bean.getNote() && bean.getNote() != null) {
				sb.append("NOTE:" + bean.getNote() + "\r\n");
			}
			if ("" != bean.getMobile() && bean.getMobile() != null) {
				sb.append("TEL;CELL:" + bean.getMobile() + "\r\n");
			}

			if ("" != bean.getTelePhone() && bean.getTelePhone() != null) {
				sb.append("TEL;HOME:" + bean.getTelePhone() + "\r\n");
			}
			if ("" != bean.getEmail() && bean.getEmail() != null) {
				sb.append("EMAIL:" + bean.getEmail() + "\r\n");
			}
			sb.append("END:VCARD\r\n");
		}
		FileUtil.writeString(vcfFile, sb.toString(), "utf-8");
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 10
Source Project: DAFramework   Source File: WJsonUtils.java    License: MIT License 5 votes vote down vote up
public static <T extends Object> T fromJson(File f, Class<T> cls) {
	try {
		return fromJson(FileUtil.readString(f, "utf-8"), cls);
	} catch (Exception e) {
		LOG.error(e.getMessage(), e);
		return null;
	}
}
 
Example 11
Source Project: DAFramework   Source File: WJsonUtils.java    License: MIT License 5 votes vote down vote up
public static JsonObjGetter fromJson(File f) {
	try {
		return fromJson(FileUtil.readString(f, "utf-8"));
	} catch (Exception e) {
		LOG.error(e.getMessage(), e);
		return null;
	}
}
 
Example 12
Source Project: DAFramework   Source File: WJsonUtils.java    License: MIT License 5 votes vote down vote up
public static void writeJson(String file, Object obj) {
	try {
		FileUtil.writeString(file, getGsonBuilder().create().toJson(obj), "utf-8");
	} catch (IOException e) {
		LOG.error(e.getMessage(), e);
	}
}
 
Example 13
Source Project: DAFramework   Source File: SysToolkit.java    License: MIT License 5 votes vote down vote up
public static void delFiles(String file) throws Exception {
	File f = new File(polishFilePath(file));
	if (f.exists()) {
		LOG.info("删除" + file);
		if (f.isDirectory()) {
			if (isSymbolicLink(file)) {
				exec("rd /q " + f.getAbsolutePath() + "", ".", true, true);
			} else {
				FileUtil.deleteDir(f.getAbsolutePath(), new FileUtilParams().setRecursive(true).setContinueOnError(false));
			}
		} else {
			FileUtil.delete(f.getAbsolutePath(), new FileUtilParams().setContinueOnError(false));
		}
	}
}
 
Example 14
Source Project: DAFramework   Source File: MenuDaoTest.java    License: MIT License 5 votes vote down vote up
@Test
public void insertAll() {
	try {
		String json = FileUtil.readString("../../WdtcWeb/static/data/allMenus.json", "utf-8");
		ActionResultList<EMenu> allMenus = WJsonUtils.toObject(json, ActionResultList.class, EMenu.class);
		Assert.notNull(allMenus, "");
		Assert.notNull(allMenus.getData(), "");
		int index = 10;
		for (EMenu menu : allMenus.getData()) {
			if (menu.getItems() != null && menu.getItems().size() > 0) {
				printMenuInsertSql(index + "", "0", menu.getName(), menu.getCode(), 10, "message");
				int subIndex1 = 10;
				for (EMenu subMenu1 : menu.getItems()) {
					if (subMenu1.getItems() != null && subMenu1.getItems().size() > 0) {
						printMenuInsertSql(index + "" + subIndex1, index + "", subMenu1.getName(), subMenu1.getCode(), 20, "message");
						int subIndex2 = 10;
						for (EMenu subMenu2 : subMenu1.getItems()) {
							printMenuInsertSql(index + "" + subIndex1 + "" + subIndex2, index + "" + subIndex1, subMenu2.getName(), subMenu2.getCode(), 1, "message");
							subIndex2 += 10;
						}
					} else {
						printMenuInsertSql(index + "" + subIndex1, index + "", subMenu1.getName(), subMenu1.getCode(), 20, "message");
					}
					subIndex1 += 10;
				}
			} else {
				printMenuInsertSql(index + "", "0", menu.getName(), menu.getCode(), 1, "message");
			}
			index += 10;
		}
	} catch (IOException e) {
		LOG.error(e.getMessage(), e);
	}
}
 
Example 15
Source Project: wES   Source File: VcfUtils.java    License: MIT License 5 votes vote down vote up
public static void exportVcf(List<VcfBean> beans, File vcfFile) {
	try {
		StringBuffer sb = new StringBuffer();
		for (VcfBean bean : beans) {
			sb.append("BEGIN:VCARD\r\n");
			sb.append("VERSION:3.0\r\n");
			sb.append("N;CHARSET=UTF-8:;‭‬‭‬‭" + bean.getFullName() + ";;;\r\n");
			sb.append("FN;CHARSET=UTF-8: ‭‬‭‬‭" + bean.getFullName() + "\r\n");
			if ("" != bean.getOrg() && bean.getOrg() != null) {
				sb.append("ORG:" + bean.getOrg() + "\r\n");
			}
			if ("" != bean.getTitle() && bean.getTitle() != null) {
				sb.append("TITLE:" + bean.getTitle() + "\r\n");
			}
			if ("" != bean.getAddress() && bean.getAddress() != null) {
				sb.append("ADR;HOME:;;;" + bean.getAddress() + ";;;\r\n");
			}
			if ("" != bean.getNote() && bean.getNote() != null) {
				sb.append("NOTE:" + bean.getNote() + "\r\n");
			}
			if ("" != bean.getMobile() && bean.getMobile() != null) {
				sb.append("TEL;CELL:" + bean.getMobile() + "\r\n");
			}

			if ("" != bean.getTelePhone() && bean.getTelePhone() != null) {
				sb.append("TEL;HOME:" + bean.getTelePhone() + "\r\n");
			}
			if ("" != bean.getEmail() && bean.getEmail() != null) {
				sb.append("EMAIL:" + bean.getEmail() + "\r\n");
			}
			sb.append("END:VCARD\r\n");
		}
		FileUtil.writeString(vcfFile, sb.toString(), "utf-8");
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 16
Source Project: wES   Source File: WJsonUtils.java    License: MIT License 5 votes vote down vote up
public static <T extends Object> T fromJson(File f, Class<T> cls) {
	try {
		return fromJson(FileUtil.readString(f, "utf-8"), cls);
	} catch (Exception e) {
		LOG.error(e.getMessage(), e);
		return null;
	}
}
 
Example 17
Source Project: wES   Source File: WJsonUtils.java    License: MIT License 5 votes vote down vote up
public static JsonObjGetter fromJson(File f) {
	try {
		return fromJson(FileUtil.readString(f, "utf-8"));
	} catch (Exception e) {
		LOG.error(e.getMessage(), e);
		return null;
	}
}
 
Example 18
Source Project: wES   Source File: WJsonUtils.java    License: MIT License 5 votes vote down vote up
public static void writeJson(String file, Object obj) {
	try {
		FileUtil.writeString(file, getGsonBuilder().create().toJson(obj), "utf-8");
	} catch (IOException e) {
		LOG.error(e.getMessage(), e);
	}
}
 
Example 19
Source Project: wES   Source File: SysToolkit.java    License: MIT License 5 votes vote down vote up
public static void delFiles(String file) throws Exception {
	File f = new File(polishFilePath(file));
	if (f.exists()) {
		LOG.info("删除" + file);
		if (f.isDirectory()) {
			if (isSymbolicLink(file)) {
				exec("rd /q " + f.getAbsolutePath() + "", ".", true, true);
			} else {
				FileUtil.deleteDir(f.getAbsolutePath(), new FileUtilParams().setRecursive(true).setContinueOnError(false));
			}
		} else {
			FileUtil.delete(f.getAbsolutePath(), new FileUtilParams().setContinueOnError(false));
		}
	}
}
 
Example 20
Source Project: wES   Source File: EsDataHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 备份es数据到backupDir目录
 *
 * @param index
 * @param type
 * @param backupDir
 */
@SuppressWarnings("unchecked")
public void backupData(String index, String type, String backupDir) {
	try {
		String path = path(backupDir, index, type);
		FileUtil.mkdirs(path);
		WPageIterator<Object> result = search(index, type, SearchQuery.MatchAll(), Object.class);
		while (result.hasNext()) {
			Object vo = result.next();
			WJsonUtils.writeJson(path + ((Map<Object, Object>) vo).get("id") + ".json", vo);
		}
	} catch (IOException e) {
		LOG.error(e.getMessage(), e);
	}
}
 
Example 21
Source Project: wES   Source File: EsDataHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 重建Index
 *
 * @param index
 */
public void reCreateIndex(String index, String type, String backupDir) {
	try {
		String path = path(backupDir, index, type + ".json");
		String json = FileUtil.readString(path, "utf-8");
		if (json != null && json.trim().length() > 0) {
			rmAllData(index, type);
			putMapping(index, type, WJsonUtils.fromJson(json, Object.class));
		}
	} catch (Exception e) {
		LOG.error(e.getMessage(), e);
	}
}
 
Example 22
Source Project: wES   Source File: EsRestSpecGen.java    License: MIT License 5 votes vote down vote up
public void writeEnumType(String type, List<String> options, String defaultValue, String description) {
	try {
		String pkg2 = pkg + ".types";
		StringBuilder javaCodes = new StringBuilder();
		javaCodes.append("package " + pkg2 + ";\n\n");

		javaCodes.append("//" + description + "\n");
		javaCodes.append("//default: " + defaultValue + "\n");
		javaCodes.append("public enum " + type + " {\n");
		String enumCodes = "";
		for (String option : options) {
			String enumName = option.toUpperCase();
			if (option.trim().length() <= 0) {
				enumName = "v";
			}
			enumCodes += "\t" + enumName + "(\"" + option + "\"),\n";
		}
		enumCodes = StringUtil.cutSuffix(enumCodes, ",\n");
		javaCodes.append(enumCodes + ";\n");

		javaCodes.append("\tprivate String name;\n");
		javaCodes.append("\t" + type + "(String name) {\n");
		javaCodes.append("\t\tthis.name = name;\n");
		javaCodes.append("\t}\n\n");
		javaCodes.append("\[email protected]\n");
		javaCodes.append("\tpublic String toString() {\n");
		javaCodes.append("\treturn this.name;\n");
		javaCodes.append("\t}\n");
		javaCodes.append("}");
		String filePath = sourceDir + pkg2.replace('.', File.separatorChar) + File.separatorChar;
		FileUtil.mkdirs(filePath);
		FileUtil.writeString(filePath + type + ".java", javaCodes.toString(), "utf-8");
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 23
Source Project: wES   Source File: EsRestSpecGen.java    License: MIT License 5 votes vote down vote up
public void writeEsHelper() {
	try {
		String pkg2 = pkg + ".client";
		StringBuilder javaCodes = new StringBuilder();
		javaCodes.append("package " + pkg2 + ";\n\n");

		javaCodes.append("import okhttp3.HttpUrl;\n");
		javaCodes.append("import okhttp3.OkHttpClient;\n");
		javaCodes.append("import org.datasays.wes.actions.*;\n");
		javaCodes.append("import org.datasays.wes.core.IConvert;\n");
		javaCodes.append("import org.datasays.wes.core.WHttpClient;\n\n");

		javaCodes.append("public class EsHelper extends WHttpClient {\n");
		javaCodes.append("\tprotected HttpUrl server;\n");
		javaCodes.append("\n");
		javaCodes.append("\tpublic EsHelper() {\n");
		javaCodes.append("\t\tsuper();\n");
		javaCodes.append("\t}\n\n");
		javaCodes.append("\tpublic void init(String server, OkHttpClient client, IConvert convert) {\n");
		javaCodes.append("\t\tif (server.trim().endsWith(\"/\")) {\n");
		javaCodes.append("\t\t\tserver = server.trim().substring(0, server.trim().length() - 1);\n");
		javaCodes.append("\t\t}\n");
		javaCodes.append("\t\tthis.server = HttpUrl.parse(server);\n");
		javaCodes.append("\t\tsuper.init(client, convert);\n");
		javaCodes.append("\t}\n\n");

		javaCodes.append(helperCodes.toString());

		javaCodes.append("}\n");

		String filePath = sourceDir + pkg2.replace('.', File.separatorChar) + File.separatorChar;
		FileUtil.mkdirs(filePath);
		FileUtil.writeString(filePath + "EsHelper.java", javaCodes.toString(), "utf-8");
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 24
Source Project: DAFramework   Source File: SysToolkit.java    License: MIT License 4 votes vote down vote up
public

	static void copyDir(String srcDir, String destDir) throws Exception {
		FileUtil.copyDir(polishFilePath(srcDir), polishFilePath(destDir));
	}
 
Example 25
Source Project: DAFramework   Source File: SysToolkit.java    License: MIT License 4 votes vote down vote up
public

	static void copyFile(String srcDir, String destDir) throws Exception {
		FileUtil.copyFile(polishFilePath(srcDir), polishFilePath(destDir));
	}
 
Example 26
Source Project: wES   Source File: SysToolkit.java    License: MIT License 4 votes vote down vote up
public

	static void copyDir(String srcDir, String destDir) throws Exception {
		FileUtil.copyDir(polishFilePath(srcDir), polishFilePath(destDir));
	}
 
Example 27
Source Project: wES   Source File: SysToolkit.java    License: MIT License 4 votes vote down vote up
public

	static void copyFile(String srcDir, String destDir) throws Exception {
		FileUtil.copyFile(polishFilePath(srcDir), polishFilePath(destDir));
	}
 
Example 28
Source Project: symphonyx   Source File: FileUploadServlet.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    if (QN_ENABLED) {
        return;
    }

    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class);
    final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class);
    final OptionQueryService optionQueryService = beanManager.getReference(OptionQueryService.class);

    try {
        final JSONObject option = optionQueryService.getOption(Option.ID_C_MISC_ALLOW_ANONYMOUS_VIEW);
        if (!"0".equals(option.optString(Option.OPTION_VALUE))) {
            if (null == userQueryService.getCurrentUser(req) && !userMgmtService.tryLogInWithCookie(req, resp)) {
                final String referer = req.getHeader("Referer");
                if (!StringUtils.contains(referer, "fangstar.net")) {
                    final String authorization = req.getHeader("Authorization");

                    LOGGER.debug("Referer [" + referer + "], Authorization [" + authorization + "]");

                    if (!StringUtils.contains(authorization, "Basic ")) {
                        resp.sendError(HttpServletResponse.SC_FORBIDDEN);

                        return;
                    } else {
                        String usernamePwd = StringUtils.substringAfter(authorization, "Basic ");
                        usernamePwd = Base64.decodeToString(usernamePwd);

                        final String username = usernamePwd.split(":")[0];
                        final String password = usernamePwd.split(":")[1];

                        if (!StringUtils.equals(username, Symphonys.get("http.basic.auth.username"))
                                || !StringUtils.equals(password, Symphonys.get("http.basic.auth.password"))) {
                            resp.sendError(HttpServletResponse.SC_FORBIDDEN);

                            return;
                        }
                    }
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Gets file failed", e);

        resp.sendError(HttpServletResponse.SC_FORBIDDEN);

        return;
    }

    final String uri = req.getRequestURI();
    String key = uri.substring("/upload/".length());
    key = StringUtils.substringBeforeLast(key, "-64.jpg"); // Erase Qiniu template
    key = StringUtils.substringBeforeLast(key, "-260.jpg"); // Erase Qiniu template

    String path = UPLOAD_DIR + key;

    if (!FileUtil.isExistingFile(new File(path))) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);

        return;
    }

    final byte[] data = IOUtils.toByteArray(new FileInputStream(path));

    final String ifNoneMatch = req.getHeader("If-None-Match");
    final String etag = "\"" + MD5.hash(new String(data)) + "\"";

    resp.addHeader("Cache-Control", "public, max-age=31536000");
    resp.addHeader("ETag", etag);
    resp.setHeader("Server", "Latke Static Server (v" + SymphonyServletListener.VERSION + ")");

    if (etag.equals(ifNoneMatch)) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

        return;
    }

    final OutputStream output = resp.getOutputStream();
    IOUtils.write(data, output);
    output.flush();

    IOUtils.closeQuietly(output);
}
 
Example 29
Source Project: jeecg   Source File: LdapUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 修改
 * 
 * @return
 * @throws IOException
 */
public static boolean modifyInformation(String dn, String employeeID,
		DirContext dc, String[] employeeArray) throws IOException {
	try {
		String[] modifyAttr = { "telephoneNumber" };
		// employeeArray.length - 1的目的去除员工编号
		ModificationItem[] modifyItems = new ModificationItem[employeeArray.length - 1];

		for (int i = 0; i < modifyAttr.length; i++) {
			String attrName = modifyAttr[i];
			Attribute attr = new BasicAttribute(attrName,
					employeeArray[i + 1]);
			modifyItems[i] = new ModificationItem(
					DirContext.REPLACE_ATTRIBUTE, attr);
		}

		/* 修改属性 */
		// Attribute attr0 = new BasicAttribute("telephoneNumber",
		// telephoneNumber);
		// modifyItems[0] = new
		// ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr0);

		/* 删除属性 */
		// Attribute attr0 = new BasicAttribute("description","陈轶");
		// modifyItems[0] = new
		// ModificationItem(DirContext.REMOVE_ATTRIBUTE, attr0);

		/* 添加属性 */
		// Attribute attr0 = new BasicAttribute("employeeID", employeeID);
		// modifyItems[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
		// attr0);

		/* 修改属性 */
		dc.modifyAttributes(dn, modifyItems);
		return true;
	} catch (NamingException e) {
		e.printStackTrace();
		System.err.println("Error: " + e.getMessage());
		FileUtil.appendString(errorFile, "Error:" + e.getMessage() + "\n");
		return false;
	}
}
 
Example 30
Source Project: jeecg   Source File: LdapUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 主函数用于测试
 * 
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

	// get AD Context
	String adAdmin = "OP031793";
	String adAdminPassword = "xxxxx";
	
	DirContext dc = getDirContext(adAdmin, adAdminPassword);

	if (dc == null) {
		//System.out.println("User or password incorrect!");
		return;
	}

	/*
	 * 假设address.txt中存在如下信息,一个是员工号,一个是手机号,当然也可以加其他内容进来 
	 * OP036616,13111111111
	 * OP018479,13122222222 
	 * OP017591,13233333333 
	 * OP032528,13244444444
	 */

	FileInputStream fileInputStream = StreamUtils
			.getFileInputStream("d:\\address.txt");
	String strFile = StreamUtils.InputStreamTOString(fileInputStream);
	String[] lineContextArray = strFile.split("\r\n");

	for (int i = 0; i < lineContextArray.length; i++) {
		if (lineContextArray[i] == null)
			continue;

		String lineContext = lineContextArray[i];
		String[] employeeArray = lineContext.split(",");

		String employeeID = employeeArray[0];
		String dn = getDN(ROOT, "", "sAMAccountName=" + employeeID, dc);

		if (dn == null) {
			FileUtil.appendString(errorFile, "Not find user:" + employeeID
					+ "\n");
			continue;
		}

		modifyInformation(dn, employeeID, dc, employeeArray);
	}
	close(dc);
}