下面列出了怎么用org.apache.http.ParseException的API类实例代码及写法,或者点击链接到github查看源代码。
private static String getAndVerifySuccessfulResponse(HttpResponse skfsResponse){
try {
String responseJsonString = EntityUtils.toString(skfsResponse.getEntity());
Common.parseJsonFromString(responseJsonString); //Response is valid JSON by parsing it
if (skfsResponse.getStatusLine().getStatusCode() != 200
|| responseJsonString == null) {
POCLogger.logp(Level.SEVERE, CLASSNAME, "verifySuccessfulCall",
"POC-ERR-5001", skfsResponse);
throw new WebServiceException(POCLogger.getMessageProperty("POC-ERR-5001"));
}
return responseJsonString;
} catch (IOException | ParseException ex) {
POCLogger.logp(Level.SEVERE, CLASSNAME, "verifySuccessfulCall",
"POC-ERR-5001", ex.getLocalizedMessage());
throw new WebServiceException(POCLogger.getMessageProperty("POC-ERR-5001"));
}
}
private static String getAndVerifySuccessfulResponse(HttpResponse skfsResponse){
try {
String responseJsonString = EntityUtils.toString(skfsResponse.getEntity());
verifyJson(responseJsonString);
if (skfsResponse.getStatusLine().getStatusCode() != 200
|| responseJsonString == null) {
WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "verifySuccessfulCall",
"WEBAUTHN-ERR-5001", skfsResponse);
throw new WebServiceException(WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-ERR-5001"));
}
return responseJsonString;
} catch (IOException | ParseException ex) {
WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "verifySuccessfulCall",
"WEBAUTHN-ERR-5001", ex.getLocalizedMessage());
throw new WebServiceException(WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-ERR-5001"));
}
}
/**
* Open website with GNPS job
*
* @param resEntity
*/
private static void openWebsite(HttpEntity resEntity) {
if (Desktop.isDesktopSupported()) {
try {
JSONObject res = new JSONObject(EntityUtils.toString(resEntity));
String url = res.getString("url");
logger.info("Response: " + res.toString());
if (url != null && !url.isEmpty())
Desktop.getDesktop().browse(new URI(url));
} catch (ParseException | IOException | URISyntaxException | JSONException e) {
logger.log(Level.SEVERE, "Error while submitting GNPS job", e);
}
}
}
protected String getHttpContent(HttpResponse response) {
HttpEntity entity = response.getEntity();
String body = null;
if (entity == null) {
return null;
}
try {
body = EntityUtils.toString(entity, "utf-8");
} catch (ParseException | IOException e) {
LOG.error("the response's content input stream is corrupt", e);
}
return body;
}
protected String getHttpContent(HttpResponse response) {
HttpEntity entity = response.getEntity();
String body = null;
if (entity == null) {
return null;
}
try {
body = EntityUtils.toString(entity, "utf-8");
} catch (ParseException | IOException e) {
LOG.error("the response's content input stream is corrupt", e);
}
return body;
}
/**
*
* @param rest
* URL for POST method
* @return String
* @throws Exception
*/
public static String doHttpPost(final String url, final String requestBody) throws Exception {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost(url);
httppost.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
StringEntity jsonEntity = new StringEntity(requestBody);
httppost.setEntity(jsonEntity);
HttpResponse httpresponse = client.execute(httppost);
int statusCode = httpresponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
return EntityUtils.toString(httpresponse.getEntity());
} else {
LOGGER.error("URL: " + url + " Body: " + requestBody);
throw new Exception(
"unable to execute post request to " + url + " because " + httpresponse.getStatusLine().getReasonPhrase());
}
} catch (ParseException parseException) {
LOGGER.error("error closing issue" + parseException);
throw parseException;
} catch (Exception exception) {
LOGGER.error("error closing issue" + exception.getMessage());
throw exception;
}
}
/**
*
* @param url for PUT method
* @param requestBody for PUT method
* @return String
* @throws Exception
*/
public static String doHttpPut(final String url, final String requestBody) throws Exception {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpPut httpput = new HttpPut(url);
httpput.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
StringEntity jsonEntity = new StringEntity(requestBody);
httpput.setEntity(jsonEntity);
HttpResponse httpresponse = client.execute(httpput);
int statusCode = httpresponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
return EntityUtils.toString(httpresponse.getEntity());
} else {
LOGGER.error(requestBody);
throw new Exception("unable to execute post request because " + httpresponse.getStatusLine().getReasonPhrase());
}
} catch (ParseException parseException) {
LOGGER.error("error closing issue" + parseException);
throw parseException;
} catch (Exception exception) {
LOGGER.error("error closing issue" + exception.getMessage());
throw exception;
}
}
/**
*
* @param rest
* URL for POST method
* @return String
* @throws Exception
*/
public static String doHttpPost(final String url, final String requestBody) throws Exception {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost(url);
httppost.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
StringEntity jsonEntity = new StringEntity(requestBody);
httppost.setEntity(jsonEntity);
HttpResponse httpresponse = client.execute(httppost);
int statusCode = httpresponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
return EntityUtils.toString(httpresponse.getEntity());
} else {
LOGGER.error(requestBody);
throw new Exception(
"unable to execute post request because " + httpresponse.getStatusLine().getReasonPhrase());
}
} catch (ParseException parseException) {
LOGGER.error("error closing issue" + parseException);
throw parseException;
} catch (Exception exception) {
LOGGER.error("error closing issue" + exception.getMessage());
throw exception;
}
}
/**
* Fetch data and scroll id.
*
* @param endPoint
* the end point
* @param _data
* the data
* @param keyField
* the key field
* @param payLoad
* the pay load
* @return the string
*/
private static String fetchDataAndScrollId(String endPoint, List<Map<String, String>> _data, String payLoad) {
try {
ObjectMapper objMapper = new ObjectMapper();
Response response = invokeAPI("GET", endPoint, payLoad);
String responseJson = EntityUtils.toString(response.getEntity());
JsonNode _info = objMapper.readTree(responseJson).at("/hits/hits");
String scrollId = objMapper.readTree(responseJson).at("/_scroll_id").textValue();
Iterator<JsonNode> it = _info.elements();
String doc;
Map<String, String> docMap;
while (it.hasNext()) {
doc = it.next().fields().next().getValue().toString();
docMap = objMapper.readValue(doc, new TypeReference<Map<String, String>>() {
});
docMap.remove("discoverydate");
docMap.remove("_loaddate");
docMap.remove("id");
_data.add(docMap);
}
return scrollId;
} catch (ParseException | IOException e) {
LOGGER.error("Error in fetchDataAndScrollId" ,e );
}
return "";
}
private static String fetchDataAndScrollId(String endPoint, Map<String, Map<String, String>> _data, String payLoad) {
try {
ObjectMapper objMapper = new ObjectMapper();
Response response = invokeAPI("GET", endPoint, payLoad);
String responseJson = EntityUtils.toString(response.getEntity());
JsonNode _info = objMapper.readTree(responseJson).at("/hits/hits");
String scrollId = objMapper.readTree(responseJson).at("/_scroll_id").textValue();
Iterator<JsonNode> it = _info.elements();
String doc;
Map<String, String> docMap;
while (it.hasNext()) {
doc = it.next().fields().next().getValue().toString();
docMap = objMapper.readValue(doc, new TypeReference<Map<String, String>>() {
});
_data.put(docMap.get("checkid")+"_"+docMap.get("accountid"), docMap);
}
return scrollId;
} catch (ParseException | IOException e) {
LOGGER.error("Error in fetchDataAndScrollId" ,e );
}
return "";
}
/**
* Fetch data and scroll id.
*
* @param endPoint the end point
* @param _data the data
* @param keyField the key field
* @param payLoad the pay load
* @return the string
*/
private static String fetchDataAndScrollId(String endPoint, Map<String, Map<String, String>> _data, String keyField,
String payLoad) {
try {
ObjectMapper objMapper = new ObjectMapper();
Response response = invokeAPI("GET", endPoint, payLoad);
String responseJson = EntityUtils.toString(response.getEntity());
JsonNode _info = objMapper.readTree(responseJson).at("/hits/hits");
String scrollId = objMapper.readTree(responseJson).at("/_scroll_id").textValue();
Iterator<JsonNode> it = _info.elements();
while (it.hasNext()) {
String doc = it.next().fields().next().getValue().toString();
Map<String, String> docMap = new ObjectMapper().readValue(doc,
new TypeReference<Map<String, String>>() {
});
_data.put(docMap.get(keyField), docMap);
docMap.remove(keyField);
}
return scrollId;
} catch (ParseException | IOException e) {
LOGGER.error("Error fetchDataAndScrollId ", e);
}
return "";
}
public static String doHttpGet(final String url, Map<String, String> headers) throws Exception {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader(PacmanRuleConstants.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
Set<Entry<String, String>> entrySet = headers.entrySet();
for (Entry<String, String> entry : entrySet) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
HttpResponse httpresponse = client.execute(httpGet);
int statusCode = httpresponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
return EntityUtils.toString(httpresponse.getEntity());
} else {
throw new Exception("unable to execute post request because "
+ httpresponse.getStatusLine().getReasonPhrase());
}
} catch (ParseException parseException) {
throw parseException;
} catch (Exception exception) {
throw exception;
}
}
private static Long calculateDuration(String date) throws java.text.ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
SimpleDateFormat dateFormat1 = new SimpleDateFormat("M/d/yyyy H:m");
Date givenDate = null;
String givenDateStr = null;
try {
givenDate = dateFormat.parse(date);
givenDateStr = dateFormat1.format(givenDate);
} catch (ParseException e) {
logger.error("Parse exception occured : ", e);
throw new RuleExecutionFailedExeption("Parse exception occured : " + e);
}
LocalDate givenLoacalDate = LocalDateTime.parse(givenDateStr, DateTimeFormatter.ofPattern("M/d/yyyy H:m"))
.toLocalDate();
LocalDate today = LocalDateTime.now().toLocalDate();
return java.time.temporal.ChronoUnit.DAYS.between(givenLoacalDate, today);
}
/**
* Fetch data and scroll id.
*
* @param endPoint
* the end point
* @param _data
* the data
* @param keyField
* the key field
* @param payLoad
* the pay load
* @return the string
*/
private static String fetchDataAndScrollId(String endPoint, Map<String, Map<String, String>> _data, String keyField,
String payLoad) {
try {
ObjectMapper objMapper = new ObjectMapper();
Response response = invokeAPI("GET", endPoint, payLoad);
String responseJson = EntityUtils.toString(response.getEntity());
JsonNode _info = objMapper.readTree(responseJson).at("/hits/hits");
String scrollId = objMapper.readTree(responseJson).at("/_scroll_id").textValue();
Iterator<JsonNode> it = _info.elements();
String doc;
Map<String, String> docMap;
while (it.hasNext()) {
doc = it.next().fields().next().getValue().toString();
docMap = objMapper.readValue(doc, new TypeReference<Map<String, String>>() {
});
_data.put(docMap.get(keyField), docMap);
docMap.remove(keyField);
}
return scrollId;
} catch (ParseException | IOException e) {
LOGGER.error("Error in fetchDataAndScrollId" ,e );
}
return "";
}
private CheckInfo performCreateOrUpdate(CheckInput input)
throws RestApiException, URISyntaxException, ParseException, IOException {
HttpPost request = new HttpPost(buildRequestUrl());
String inputString =
JsonBodyParser.createRequestBody(input, new TypeToken<CheckInput>() {}.getType());
request.setEntity(new StringEntity(inputString));
request.setHeader("Content-type", "application/json");
try (CloseableHttpResponse response = client.execute(request)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return JsonBodyParser.parseResponse(
EntityUtils.toString(response.getEntity()), new TypeToken<CheckInfo>() {}.getType());
}
throw new RestApiException(
String.format("Request returned status %s", response.getStatusLine().getStatusCode()));
}
}
/**
* @throws IOException
* @throws ParseException
* @方法名 start
* @功能 TODO(这里用一句话描述这个方法的作用)
* @参数 @param list
* @参数 @return
* @返回 String
* @author Administrator
* @throws
*/
public String start(List<SysCrawlerRulerInfo> list) throws ParseException, IOException {
for (SysCrawlerRulerInfo sysCrawlerRulerInfo : list) {
if ("0".equals(sysCrawlerRulerInfo.getStatue())) {
// 启动任务
Map<String, String> map = new HashMap<>();
map.put("uuid", sysCrawlerRulerInfo.getUuid());
map.put("taskUuid", sysCrawlerRulerInfo.getUuid());
map.put("contentInfo", sysCrawlerRulerInfo.getContentJsonInfo());
map.put("delete", sysCrawlerRulerInfo.getDeleteFlag() + "");
map.put("statue", "1");
HttpUtil.postJson("http://127.0.0.1:3000/crawler", map, "UTF-8");
}
sysCrawlerRulerInfo.setStatue("1");
sysCrawlerRulerInfoDao.save(sysCrawlerRulerInfo);
}
return "1";
}
/**
* POST请求
*
* @param url URL
* @param parameterMap 请求参数
* @param encoding 编码格式
* @return 返回结果
*/
public static String post(String url, Map<String, ?> parameterMap, String encoding) {
String result = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<>();
if (parameterMap != null) {
parameterMap.forEach((k, v) -> {
String value = String.valueOf(v);
if (StringUtils.isNoneEmpty(value)) {
nameValuePairs.add(new BasicNameValuePair(k, value));
}
});
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, encoding));
CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpPost);
result = consumeResponse(httpResponse, encoding);
} catch (ParseException | IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
return result;
}
/**
* GET请求
*
* @param url URL
* @param parameterMap 请求参数
* @return 返回结果
*/
public static String get(String url, Map<String, ?> parameterMap) {
String result = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (parameterMap != null) {
parameterMap.forEach((k, v) -> {
String value = String.valueOf(v);
if (StringUtils.isNoneEmpty(value)) {
nameValuePairs.add(new BasicNameValuePair(k, value));
}
});
}
HttpGet httpGet = new HttpGet(url + (url.contains("?") ? "&" : "?") + EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpGet);
result = consumeResponse(httpResponse, "UTF-8");
} catch (ParseException | IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
return result;
}
@Test
public void valid() {
Header[] headers = {new Header() {
public String getName() {
return "session_id";
}
public String getValue() {
return "12345";
}
public HeaderElement[] getElements() throws ParseException {
return new HeaderElement[0];
}
}};
ApiClientResponse response = new ApiClientResponse(headers, "{\"key\":\"value\"}");
assertEquals("12345", response.getHeader("session_id"));
assertEquals("{\n \"key\" : \"value\"\n}", response.toJson());
assertEquals("value", response.getField("key"));
}
/**
* 简单远程请求
*
* @param type
* @param kind
* @param url
* @param data
* @param head
* @return
* @throws HongsException
* @throws StatusException
* @throws SimpleException
*/
public static String request(METHOD type, FORMAT kind, String url, Map<String, Object> data, Map<String, String> head)
throws HongsException, StatusException, SimpleException {
final String [ ] txt = new String [1];
final SimpleException[ ] err = new SimpleException[1];
request(type, kind, url, data, head, (rsp) -> {
try {
txt[0] = EntityUtils.toString(rsp.getEntity(), "UTF-8").trim();
} catch (IOException | ParseException ex) {
err[0] = new SimpleException(url, ex);
}
});
if (null != err[0]) {
throw err[0];
} return txt[0];
}
private void addMockedHeader(
final HttpResponse httpResponseMock,
final String name,
final String value,
HeaderElement[] elements) {
final Header header = new Header() {
@Override
public String getName() {
return name;
}
@Override
public String getValue() {
return value;
}
@Override
public HeaderElement[] getElements() throws ParseException {
return elements;
}
};
when(httpResponseMock.getFirstHeader(name)).thenReturn(header);
}
public boolean createFolder(String path, String name) {
log.debug("File Station createFolder");
boolean ret = false;
try {
baseUrl = "http://" + settingService.getSettingValue("DS_HOST") + ":"
+ settingService.getSettingValue("DS_PORT") + "/webapi";
URIBuilder builder = new URIBuilder(baseUrl + "/entry.cgi");
builder.setParameter("api", "SYNO.FileStation.CreateFolder").setParameter("version", "2")
.setParameter("method", "create").setParameter("folder_path", "[\"" + path + "\"]")
.setParameter("name", "[\"" + name + "\"]").setParameter("force_parent", "true")
.setParameter("_sid", sid);
JSONObject resJson = executeGet(builder);
log.debug(builder.toString());
if (resJson != null) {
log.debug(resJson.toString());
if (resJson.has("success")) {
if (Boolean.parseBoolean(resJson.get("success").toString())) {
// JSONArray jsonArray = resJson.getJSONObject("data").getJSONArray("folders");
ret = true;
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return ret;
}
public JSONArray list(String path, String name) {
try {
baseUrl = "http://" + settingService.getSettingValue("DS_HOST") + ":"
+ settingService.getSettingValue("DS_PORT") + "/webapi";
String folderPath = path + "/" + name;
URIBuilder builder = new URIBuilder(baseUrl + "/entry.cgi");
builder.setParameter("api", "SYNO.FileStation.List").setParameter("version", "2")
.setParameter("method", "list").setParameter("folder_path", folderPath).setParameter("_sid", sid);
JSONObject resJson = executeGet(builder);
log.debug(builder.toString());
if (resJson != null) {
log.debug(resJson.toString());
if (resJson.has("success")) {
if (Boolean.parseBoolean(resJson.get("success").toString())) {
if (resJson.has("data")) {
if (resJson.getJSONObject("data").has("files")) {
return resJson.getJSONObject("data").getJSONArray("files");
}
}
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return null;
}
public String move(List<String> paths, String dest) {
log.debug("File Station CopyMove");
String taskId = null;
try {
baseUrl = "http://" + settingService.getSettingValue("DS_HOST") + ":"
+ settingService.getSettingValue("DS_PORT") + "/webapi";
String path = "[\"" + StringUtils.join(paths, "\",\"") + "\"]";
URIBuilder builder = new URIBuilder(baseUrl + "/entry.cgi");
builder.setParameter("api", "SYNO.FileStation.CopyMove").setParameter("version", "3")
.setParameter("method", "start").setParameter("path", path).setParameter("dest_folder_path", dest)
.setParameter("overwrite", "true").setParameter("remove_src", "true").setParameter("_sid", sid);
JSONObject resJson = executeGet(builder);
log.debug(builder.toString());
if (resJson != null) {
log.debug(resJson.toString());
if (resJson.has("success")) {
if (Boolean.parseBoolean(resJson.get("success").toString())) {
if (resJson.has("data")) {
if (resJson.getJSONObject("data").has("taskid")) {
taskId = resJson.getJSONObject("data").getString("taskid");
}
}
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return taskId;
}
public boolean delete(String path) {
log.debug("File Station Delete");
boolean ret = false;
try {
baseUrl = "http://" + settingService.getSettingValue("DS_HOST") + ":"
+ settingService.getSettingValue("DS_PORT") + "/webapi";
URIBuilder builder = new URIBuilder(baseUrl + "/entry.cgi");
builder.setParameter("api", "SYNO.FileStation.Delete").setParameter("version", "2")
.setParameter("method", "start").setParameter("path", path).setParameter("recursive", "true")
.setParameter("_sid", sid);
JSONObject resJson = executeGet(builder);
log.debug(builder.toString());
if (resJson != null) {
log.debug(resJson.toString());
if (resJson.has("success")) {
if (Boolean.parseBoolean(resJson.get("success").toString())) {
ret = true;
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return ret;
}
public boolean rename(String path, String name) {
log.debug("File Station Rename");
boolean ret = false;
try {
baseUrl = "http://" + settingService.getSettingValue("DS_HOST") + ":"
+ settingService.getSettingValue("DS_PORT") + "/webapi";
URIBuilder builder = new URIBuilder(baseUrl + "/entry.cgi");
builder.setParameter("api", "SYNO.FileStation.Rename").setParameter("version", "2")
.setParameter("method", "rename").setParameter("path", path).setParameter("name", name)
.setParameter("_sid", sid);
JSONObject resJson = executeGet(builder);
log.debug(builder.toString());
if (resJson != null) {
log.debug(resJson.toString());
if (resJson.has("success")) {
if (Boolean.parseBoolean(resJson.get("success").toString())) {
ret = true;
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return ret;
}
public List<DownloadList> list() {
log.debug("Download Station list");
List<DownloadList> ret = new ArrayList<DownloadList>();
try {
URIBuilder builder = new URIBuilder(baseUrl + "/DownloadStation/task.cgi");
builder.setParameter("api", "SYNO.DownloadStation.Task").setParameter("version", "3")
.setParameter("method", "list").setParameter("additional", "detail,transfer")
.setParameter("_sid", this.sid);
JSONObject resJson = executeGet(builder);
if(resJson != null) {
if(resJson.has("success")) {
if(Boolean.parseBoolean(resJson.get("success").toString())) {
if(resJson.has("data")) {
if(resJson.getJSONObject("data").has("tasks")) {
JSONArray jsonArray = resJson.getJSONObject("data").getJSONArray("tasks");
for(int i = 0; i < jsonArray.length(); i ++) {
DownloadList down = setInfo(jsonArray.getJSONObject(i));
ret.add(down);
}
}
}
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return ret;
}
public DownloadList getInfo(String id) {
log.debug("Download Station getInfo");
DownloadList ret = null;
try {
URIBuilder builder = new URIBuilder(baseUrl + "/DownloadStation/task.cgi");
builder.setParameter("api", "SYNO.DownloadStation.Task").setParameter("version", "3")
.setParameter("method", "getinfo").setParameter("additional", "detail,transfer")
.setParameter("id", id).setParameter("_sid", this.sid);
JSONObject resJson = executeGet(builder);
if(resJson != null) {
if(resJson.has("success")) {
if(Boolean.parseBoolean(resJson.get("success").toString())) {
JSONArray jsonArray = resJson.getJSONObject("data").getJSONArray("tasks");
ret = setInfo(jsonArray.getJSONObject(0));
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return ret;
}
public List<DownloadList> getInfo(List<String> ids) {
log.debug ("Download Station getInfo");
List<DownloadList> ret = new ArrayList<DownloadList>();
try {
URIBuilder builder = new URIBuilder(baseUrl + "/DownloadStation/task.cgi");
builder.setParameter("api", "SYNO.DownloadStation.Task").setParameter("version", "3")
.setParameter("method", "getinfo").setParameter("additional", "detail,transfer")
.setParameter("id", StringUtils.join(ids, ",")).setParameter("_sid", this.sid);
JSONObject resJson = executeGet(builder);
if(resJson != null) {
if(Boolean.parseBoolean(resJson.get("success").toString())) {
JSONArray jsonArray = resJson.getJSONObject("data").getJSONArray("tasks");
for(int i = 0; i < jsonArray.length(); i++) {
ret.add(setInfo(jsonArray.getJSONObject(i)));
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return ret;
}
public boolean delete(List<String> ids) {
log.debug("Download Station delete");
boolean ret = true;
try {
URIBuilder builder = new URIBuilder(baseUrl + "/DownloadStation/task.cgi");
builder.setParameter("api", "SYNO.DownloadStation.Task").setParameter("version", "3")
.setParameter("method", "delete").setParameter("force_complete", "false")
.setParameter("id", StringUtils.join(ids, ",")).setParameter("_sid", this.sid);
JSONObject resJson = executeGet(builder);
if(resJson != null) {
if(resJson.has("data")) {
JSONArray jarray = resJson.getJSONArray("data");
for(int i = 0; i <jarray.length(); i++) {
if(jarray.getJSONObject(i).has("error")) {
if(jarray.getJSONObject(i).getInt("error") > 0) {
ret = false;
break;
}
}
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return ret;
}