Java Code Examples for com.zhazhapan.util.Checker#isNotNull()

The following examples show how to use com.zhazhapan.util.Checker#isNotNull() . 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
Source File: FileController.java    From efo with MIT License 6 votes vote down vote up
@ApiOperation(value = "获取文件记录")
@ApiImplicitParams({@ApiImplicitParam(name = "offset", value = "偏移量", required = true), @ApiImplicitParam(name =
        "categoryId", value = "分类ID", required = true), @ApiImplicitParam(name = "orderBy", value = "排序方式",
        required = true, example = "id desc"), @ApiImplicitParam(name = "search", value = "记录匹配(允许为空)")})
@AuthInterceptor(InterceptorLevel.NONE)
@RequestMapping(value = "/all", method = RequestMethod.GET)
public String getAll(int offset, int categoryId, String orderBy, String search) {
    User user = (User) request.getSession().getAttribute(ValueConsts.USER_STRING);
    boolean canGet = EfoApplication.settings.getBooleanUseEval(ConfigConsts.ANONYMOUS_VISIBLE_OF_SETTING) ||
            (Checker.isNotNull(user) && user.getIsVisible() == 1);
    if (canGet) {
        int userId = Checker.isNull(user) ? 0 : user.getId();
        return Formatter.listToJson(fileService.listAll(userId, offset, categoryId, orderBy, search));
    } else {
        jsonObject.put("error", "权限被限制,无法获取资源,请联系管理员");
        return jsonObject.toString();
    }
}
 
Example 2
Source File: QiniuService.java    From qiniu with MIT License 6 votes vote down vote up
/**
 * 获取空间的流量统计,使用自定义单位
 */
public XYChart.Series<String, Long> getBucketFlux(String[] domains, String startDate, String endDate, String unit) {
    // 获取流量数据
    CdnResult.FluxResult fluxResult = null;
    try {
        fluxResult = sdkManager.getFluxData(domains, startDate, endDate);
    } catch (QiniuException e) {
        Platform.runLater(() -> DialogUtils.showException(QiniuValueConsts.BUCKET_FLUX_ERROR, e));
    }
    // 设置图表
    XYChart.Series<String, Long> series = new XYChart.Series<>();
    series.setName(QiniuValueConsts.BUCKET_FLUX_COUNT.replaceAll("[A-Z]+", unit));
    // 格式化数据
    if (Checker.isNotNull(fluxResult) && Checker.isNotEmpty(fluxResult.data)) {
        long unitSize = Formatter.sizeToLong("1 " + unit);
        for (Map.Entry<String, CdnResult.FluxData> flux : fluxResult.data.entrySet()) {
            CdnResult.FluxData fluxData = flux.getValue();
            if (Checker.isNotNull(fluxData)) {
                setSeries(fluxResult.time, fluxData.china, fluxData.oversea, series, unitSize);
            }
        }
    }
    return series;
}
 
Example 3
Source File: FileManagerServiceImpl.java    From efo with MIT License 6 votes vote down vote up
@Override
public JSONObject upload(String destination, MultipartFile... files) {
    System.out.println(files.length);
    if (Checker.isNotEmpty(files)) {
        if (Checker.isWindows() && destination.length() < ValueConsts.TWO_INT) {
            destination = "C:";
        }
        for (MultipartFile file : files) {
            if (Checker.isNotNull(file) && !file.isEmpty()) {
                try {
                    file.transferTo(new File(destination + File.separator + file.getOriginalFilename()));
                } catch (IOException e) {
                    logger.error(e.getMessage());
                    return getBasicResponse(ValueConsts.FALSE);
                }
            }
        }
    }
    return getBasicResponse(ValueConsts.TRUE);
}
 
Example 4
Source File: UserServiceImpl.java    From efo with MIT License 6 votes vote down vote up
@Override
public User login(String loginName, String password, String token, HttpServletResponse response) {
    boolean allowLogin = settings.getBooleanUseEval(ConfigConsts.ALLOW_LOGIN_OF_SETTINGS);
    User user = null;
    if (allowLogin) {
        if (Checker.isNotEmpty(token) && EfoApplication.tokens.containsKey(token)) {
            user = userDAO.getUserById(EfoApplication.tokens.get(token));
            if (Checker.isNotNull(response)) {
                Cookie cookie = new Cookie(ValueConsts.TOKEN_STRING, TokenConfig.generateToken(token, user.getId
                        ()));
                cookie.setMaxAge(30 * 24 * 60 * 60);
                response.addCookie(cookie);
            }
        }
        if (Checker.isNull(user) && Checker.isNotEmpty(loginName) && Checker.isNotEmpty(password)) {
            user = userDAO.login(loginName, password);
            if (Checker.isNotNull(user)) {
                TokenConfig.removeTokenByValue(user.getId());
            }
        }
        updateUserLoginTime(user);
    }
    return user;
}
 
Example 5
Source File: QiniuService.java    From qiniu with MIT License 6 votes vote down vote up
/**
 * 获取空间带宽统计,使用自定义单位
 */
public XYChart.Series<String, Long> getBucketBandwidth(String[] domains, String startDate, String endDate,
                                                       String unit) {
    // 获取带宽数据
    CdnResult.BandwidthResult bandwidthResult = null;
    try {
        bandwidthResult = sdkManager.getBandwidthData(domains, startDate, endDate);
    } catch (QiniuException e) {
        Platform.runLater(() -> DialogUtils.showException(QiniuValueConsts.BUCKET_BAND_ERROR, e));
    }
    // 设置图表
    XYChart.Series<String, Long> series = new XYChart.Series<>();
    series.setName(QiniuValueConsts.BUCKET_BANDWIDTH_COUNT.replaceAll("[A-Z]+", unit));
    // 格式化数据
    if (Checker.isNotNull(bandwidthResult) && Checker.isNotEmpty(bandwidthResult.data)) {
        long unitSize = Formatter.sizeToLong("1 " + unit);
        for (Map.Entry<String, CdnResult.BandwidthData> bandwidth : bandwidthResult.data.entrySet()) {
            CdnResult.BandwidthData bandwidthData = bandwidth.getValue();
            if (Checker.isNotNull(bandwidthData)) {
                setSeries(bandwidthResult.time, bandwidthData.china, bandwidthData.oversea, series, unitSize);
            }
        }
    }
    return series;
}
 
Example 6
Source File: MainController.java    From qiniu with MIT License 6 votes vote down vote up
/**
 * 添加上传的文件,支持拖曳文件夹
 */
private void appendFile(File[] files, boolean isRecursive) {
    if (Checker.isNotNull(files)) {
        for (File file : files) {
            if (file.isDirectory()) {
                if (isRecursive) {
                    // 递归添加文件
                    if (recursiveCB.isSelected()) {
                        appendFile(file.listFiles(), true);
                    }
                } else {
                    rootPath.add(file.getAbsolutePath());
                    appendFile(file.listFiles(), true);
                }
            } else if (!selectedFileTA.getText().contains(file.getAbsolutePath())) {
                selectedFileTA.insertText(0, file.getAbsolutePath() + "\r\n");
            }
        }
    }
}
 
Example 7
Source File: MainController.java    From visual-spider with MIT License 6 votes vote down vote up
/**
 * 连接到数据库
 */
private void connectDatabase() {
    try {
        if (Checker.isNotNull(SpiderApplication.connection) && !SpiderApplication.connection.isClosed()) {
            SpiderApplication.connection.close();
        }
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://" + MysqlConfig.getDbHost() + ":" + MysqlConfig.getDbPort() + "/" +
                MysqlConfig.getDbName() + "?" + MysqlConfig.getDbCondition();
        SpiderApplication.connection = DriverManager.getConnection(url, MysqlConfig.getDbUsername(), MysqlConfig
                .getDbPassword());
        SpiderApplication.statement = SpiderApplication.connection.createStatement();
        LOGGER.info("database connect success");
        MysqlConfig.setConnectionSuccessful(true);
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        MysqlConfig.setConnectionSuccessful(false);
        Alerts.showError(SpiderValueConsts.MAIN_TITLE, e.getMessage());
    }
}
 
Example 8
Source File: MainController.java    From visual-spider with MIT License 6 votes vote down vote up
/**
 * 退出程序
 */
public void exit() {
    if (crawling) {
        Optional<ButtonType> result = Alerts.showConfirmation(SpiderValueConsts.MAIN_TITLE, SpiderValueConsts
                .EXIT_CRAWLING);
        if (result.get() != ButtonType.OK) {
            return;
        }
    }
    saveLog();
    // 关闭数据库连接
    try {
        if (Checker.isNotNull(SpiderApplication.statement)) {
            SpiderApplication.statement.close();
        }
        if (Checker.isNotNull(SpiderApplication.connection)) {
            SpiderApplication.connection.close();
        }
    } catch (SQLException e) {
        LOGGER.error(e.getMessage());
    }
    System.exit(0);
}
 
Example 9
Source File: GsonTest.java    From qiniu with MIT License 5 votes vote down vote up
@Test
public void testGson() {
	JsonObject json = new JsonParser().parse(configJson).getAsJsonObject();
	JsonElement buckets = json.get("buckets");
	if (Checker.isNotNull(buckets)) {
		JsonArray array = buckets.getAsJsonArray();
		for (JsonElement element : array) {
			System.out.println(((JsonObject) element).get("bucket").getAsString());
		}
	}
}
 
Example 10
Source File: MainController.java    From visual-spider with MIT License 5 votes vote down vote up
/**
 * 删除文件夹或文件
 *
 * @param file {@link File}
 */
public void deleteFile(File file) {
    if (file.exists()) {
        if (file.isDirectory()) {
            String[] children = file.list();
            if (Checker.isNotNull(children)) {
                for (String aChildren : children) {
                    deleteFile(new File(file, aChildren));
                }
            }
        }
        file.delete();
    }
}
 
Example 11
Source File: UserServiceImpl.java    From efo with MIT License 5 votes vote down vote up
@Override
public void updateUserLoginTime(User user) {
    if (Checker.isNotNull(user)) {
        user.setLastLoginTime(DateUtils.getCurrentTimestamp());
        userDAO.updateUserLoginTime(user.getId());
    }
}
 
Example 12
Source File: FileController.java    From efo with MIT License 5 votes vote down vote up
@ApiOperation(value = "通过文件路径获取服务器端的文件")
@ApiImplicitParam(name = "path", value = "文件路径(默认根目录)")
@AuthInterceptor(InterceptorLevel.ADMIN)
@RequestMapping(value = "/server", method = RequestMethod.GET)
public String getServerFilesByPath(String path) {
    File[] files = FileExecutor.listFile(Checker.isEmpty(path) ? (Checker.isWindows() ? "C:\\" : "/") : path);
    JSONArray array = new JSONArray();
    if (Checker.isNotNull(files)) {
        for (File file : files) {
            array.add(BeanUtils.beanToJson(file));
        }
    }
    return array.toJSONString();
}
 
Example 13
Source File: MainController.java    From visual-spider with MIT License 4 votes vote down vote up
/**
 * 打开自定义爬取面板
 */
public void customCrawling() {
    Dialog<ButtonType> dialog = new Dialog<>();
    dialog.setTitle(SpiderValueConsts.MAIN_TITLE);
    dialog.setHeaderText(null);
    dialog.initModality(Modality.APPLICATION_MODAL);
    ButtonType ok = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
    ButtonType cancel = new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE);
    try {
        DialogPane dialogPane = FXMLLoader.load(getClass().getResource("/view/CustomCrawling.fxml"));
        dialogPane.getButtonTypes().addAll(ok, cancel);
        dialog.setDialogPane(dialogPane);
        Optional<ButtonType> result = dialog.showAndWait();
        if (ok.equals(result.get())) {
            //设置配置信息
            CustomCrawlingController controller = SpiderApplication.customCrawlingController;
            if (Checker.isNotNull(controller)) {
                String mappings = controller.mappings.getText();
                boolean enableCustom = controller.enableCustomCrawling.isSelected();
                if (enableCustom && Checker.isNotEmpty(mappings)) {
                    MysqlConfig.setDbCondition(controller.dbCondition.getText());
                    MysqlConfig.setDbHost(controller.dbHost.getText());
                    MysqlConfig.setDbName(controller.dbName.getText());
                    MysqlConfig.setDbPassword(controller.dbPassword.getText());
                    MysqlConfig.setDbPort(controller.dbPort.getText());
                    MysqlConfig.setDbUsername(controller.dbUsername.getText());
                    MysqlConfig.setTableName(controller.dbTable.getText());
                    MysqlConfig.setEnableCustom(true);
                    MysqlConfig.setEnableSql(controller.enableSql.isSelected());
                    String[] mapping = mappings.split(ValueConsts.COMMA_SIGN);
                    MysqlConfig.getFields().clear();
                    for (String s : mapping) {
                        String[] keyValue = s.split("->");
                        Pair<String, String> map = new Pair<>(keyValue[0].trim(), keyValue[1].trim());
                        MysqlConfig.getFields().add(map);
                    }
                    connectDatabase();
                } else {
                    MysqlConfig.setEnableCustom(false);
                    if (enableCustom) {
                        Alerts.showWarning(SpiderValueConsts.MAIN_TITLE, "映射关系为空,无法开启自定义爬取");
                    }
                }
            }
        }
    } catch (IOException e) {
        Alerts.showError(SpiderValueConsts.MAIN_TITLE, e.getMessage());
    }
    customCK.setSelected(MysqlConfig.isEnableCustom());
}
 
Example 14
Source File: VsController.java    From visual-spider with MIT License 4 votes vote down vote up
/**
 * 关闭爬虫,不可恢复
 */
public void shutdown() {
    if (Checker.isNotNull(controller)) {
        controller.shutdown();
    }
}
 
Example 15
Source File: MainController.java    From qiniu with MIT License 4 votes vote down vote up
/**
 * 显示移动或复制文件的弹窗
 */
public void showFileMovableDialog() {
    ObservableList<FileBean> selectedItems = resTV.getSelectionModel().getSelectedItems();
    if (Checker.isEmpty(selectedItems)) {
        // 没有选择文件,结束方法
        return;
    }
    Pair<SdkManager.FileAction, String[]> resultPair;
    String bucket = bucketCB.getValue();
    if (selectedItems.size() > 1) {
        resultPair = dialog.showFileDialog(bucket, "", false);
    } else {
        resultPair = dialog.showFileDialog(bucket, selectedItems.get(0).getName(), true);
    }
    if (Checker.isNotNull(resultPair)) {
        boolean useNewKey = Checker.isNotEmpty(resultPair.getValue()[1]);
        ObservableList<FileBean> fileBeans = resTV.getItems();
        for (FileBean fileBean : selectedItems) {
            String fromBucket = bucketCB.getValue();
            String toBucket = resultPair.getValue()[0];
            String name = useNewKey ? resultPair.getValue()[1] : fileBean.getName();
            boolean isSuccess = service.moveOrCopyFile(fromBucket, fileBean.getName(), toBucket, name,
                    resultPair.getKey());
            if (resultPair.getKey() == SdkManager.FileAction.MOVE && isSuccess) {
                boolean isInSearch = Checker.isNotEmpty(searchTF.getText());
                if (fromBucket.equals(toBucket)) {
                    // 更新文件名
                    fileBean.setName(name);
                    if (isInSearch) {
                        fileBeans.get(fileBeans.indexOf(fileBean)).setName(name);
                    }
                } else {
                    // 删除数据源
                    fileBeans.remove(fileBean);
                    dataLength--;
                    dataSize -= Formatter.sizeToLong(fileBean.getSize());
                    if (isInSearch) {
                        fileBeans.remove(fileBean);
                    }
                }
            }
        }
        countBucket();
    }
}
 
Example 16
Source File: CategoryServiceImpl.java    From efo with MIT License 4 votes vote down vote up
@Override
public boolean insert(String name) {
    return Checker.isNotNull(name) && categoryDAO.insertCategory(name);
}
 
Example 17
Source File: WebInterceptor.java    From efo with MIT License 4 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
        Exception {
    String url = request.getServletPath();
    InterceptorLevel level = InterceptorLevel.NONE;
    if (handler instanceof HandlerMethod) {
        AuthInterceptor interceptor = ((HandlerMethod) handler).getMethodAnnotation(AuthInterceptor.class);
        //注解到类上面的注解,无法直接获取,只能通过扫描
        if (Checker.isNull(interceptor)) {
            for (Class<?> type : EfoApplication.controllers) {
                RequestMapping mapping = type.getAnnotation(RequestMapping.class);
                if (Checker.isNotNull(mapping)) {
                    for (String path : mapping.value()) {
                        if (url.startsWith(path)) {
                            interceptor = type.getAnnotation(AuthInterceptor.class);
                            break;
                        }
                    }
                    break;
                }
            }
        }
        if (Checker.isNotNull(interceptor)) {
            level = interceptor.value();
        }
    }
    User user = (User) request.getSession().getAttribute(ValueConsts.USER_STRING);
    if (Checker.isNull(user)) {
        //读取token,自动登录
        Cookie cookie = HttpUtils.getCookie(ValueConsts.TOKEN_STRING, request.getCookies());
        if (Checker.isNotNull(cookie)) {
            user = userService.login(ValueConsts.EMPTY_STRING, ValueConsts.EMPTY_STRING, cookie.getValue(),
                    response);
            if (Checker.isNotNull(user)) {
                request.getSession().setAttribute(ValueConsts.USER_STRING, user);
            }
        }
    }
    if (level != InterceptorLevel.NONE) {
        boolean isRedirect = Checker.isNull(user) || (level == InterceptorLevel.ADMIN && user.getPermission() <
                2) || (level == InterceptorLevel.SYSTEM && user.getPermission() < 3);
        if (isRedirect) {
            response.sendRedirect(DefaultValues.SIGNIN_PAGE);
            return false;
        }
    }
    return true;
}